Professional Documents
Culture Documents
And
Algorithms
DCS/CSC -204
www.ubids.edu.gh.com 1
AIM
❖ Introduce students to :
www.ubids.edu.gh.com 2
Course Outline
❑Definition of Data structure
❑Types of Data Structures
❑ Implementations in C++
✓ List
✓ Stacks
✓ Queue
www.ubids.edu.gh.com 3
Reading Materials:
1. Jay Wengrow (2020) A Common-Sense Gide to Data Structures
and Algorithms (Second Edition). The Pragmatic Programmers,
LLC.
www.ubids.edu.gh.com 4
What is Data Structure?
❖Data Structure is a particular way arranging, storing and
organizing data in the memory of the computer so that the data
can easily be retrieved and efficiently utilized in the future when
required.
www.ubids.edu.gh.com 5
What is Data Structure?
❖The choice of data structure for a particular task depends on
the type and amount of data to be processed, the operations
that need to be performed on the data, and the efficiency
requirements of the program.
www.ubids.edu.gh.com 6
Why should we learn Data Structures?
1) Data Structures and Algorithms are two of the key aspects of
Computer Science.
www.ubids.edu.gh.com 8
Significant Features of Data Structures
www.ubids.edu.gh.com 9
Significant Features of Data Structures
www.ubids.edu.gh.com 10
Basic terminologies related to Data Structures
Data Structures are the building blocks of any software or
program. Selecting the suitable data structure for a program is an
extremely challenging task for a programmer.
✓Data: We can define data as an elementary value or a
collection of values. For example, the Employee's name and
ID are the data related to the Employee.
✓Data Items: A single unit of value is known as Data Item.
www.ubids.edu.gh.com 11
Basic terminologies related to Data
Structures
✓ Field: A single elementary unit of information symbolizing the
Attribute of an Entity is known as Field.
✓ Record: A collection of different data items are known as a
Record. For example, if we talk about the employee entity, then
its name, id, address, and job title can be grouped to form the
record for the employee.
✓Elementary Items: Data Items that are unable to divide into sub-
items are known as Elementary Items. For example, the ID of an
Employee.
✓Entity and Attribute: A class of certain objects is represented by
an Entity. It consists of different Attributes. Each Attribute
symbolizes the specific property of that Entity. For example
www.ubids.edu.gh.com 12
✓File: A collection of different records of one entity type is known as a
File. For example, if there are 100 employees, there will be 25 records in
the related file containing data about each employee
www.ubids.edu.gh.com 13
Types of Data Structures
Data Structures
Primitive Non-Primitive
Structure Data Structure
Linear Non-linear
int
(Sequential) (Random)
One-Dimensional Non-directional
duoble Siingle-linked list Binary Search Trees
Arrays graphs
Two -Dimensioanl
Pointer Double-Linked List B-trees
Arrays
Multi-dimensional
Arrays Circular-Linked List AVL tree
www.ubids.edu.gh.com 14
Primitive Data Structures
❖Primitive data structures: These are the most basic and
predefined data structures and are usually built into programming
languages.
❖Examples include:
✓Integer
✓Float
✓Character
✓Boolean
✓Double
✓Pointer
✓Void www.ubids.edu.gh.com 15
Non-Primitive Data structures
❖Non-primitive data structures: These are complex data structures
that are built using primitive data types.
❖ Non-primitive data structures can be further categorized into the
following types:
✓Arrays: A collection of elements of the same data type, stored in
contiguous memory locations.
✓Linked lists: A collection of elements that are connected by links
or pointers.
✓Stacks: A collection of elements that follow the Last-In-First-Out
(LIFO) principle.
www.ubids.edu.gh.com 16
Non-Primitive data structures
✓Queues: A collection of elements that follow the First-In-
First-Out (FIFO) principle.
www.ubids.edu.gh.com 17
Differences between
Primitive and Non-Primitive Data Structures
Primitive Data Types Non-Primitive Data Types
1. Primitive data types are 1. Non-primitive data types are
predefined and provided by the
created by the programmer and are
programming language. also called user-defined data types.
2. They are atomic and store a
2. They are composite and store a
single value. collection of values or objects.
3.Primitive data types have a
3. Non-primitive data types can
fixed size in memory. have varying sizes depending on the
number of elements or objects they
contain.
4. They are passed by value 4. They are passed by reference,
when used as arguments in which means a reference to the
methods or functions. original object is passed rather than
the object itself.
www.ubids.edu.gh.com 18
Differences between
Primitive and Non-Primitive Data Structures
5. Primitive data types are stored 1. Non-primitive data types are
on the stack. stored on the heap.
6. They are initialized with default 6. Non-primitive data types need
values automatically (e.g., 0 for to be explicitly initialized by the
integers, false for booleans). programmer.
7. Primitive data types include 7. Non-primitive data types
integers, floating-point numbers, include arrays, strings, classes,
characters, booleans, structures, etc.
etc.
8. They have a limited set of 8. Non-primitive data types can
operations that can be performed have custom operations defined
directly on them (e.g., arithmetic by the programmer through
operations on numbers). methods or functions. 19
www.ubids.edu.gh.com
Differences between
Primitive and Non-Primitive Data Structures
9. Primitive data types are 9. Non-primitive data types may
generally faster to access and require more complex operations
manipulate. and have a higher overhead in
terms of performance.
10. They have a shorter lifespan 10. Non-primitive data types can
as they are short-lived and are have a longer lifespan as they can
destroyed as soon as they go out be dynamically allocated and
of scope. deallocated during program
execution
www.ubids.edu.gh.com 20
www.ubids.edu.gh.com 21
Linear Data Structure
❖ A Linear data structure is a type of data structure in which
data elements are arranged in a sequential order, and each
element has a unique predecessor and successor, except for the
first and last elements. Linear data structures are one-
dimensional and can be traversed sequentially from the first to
the last element. Elements are arranged in one dimension ,also
known as linear dimension.
Element 1 Element 2 Element 3 Element 4 Element 5 Element 5 ...
www.ubids.edu.gh.com 22
Linear Data Structure
Arrays Queues
Single-Linked list
Stacks www.ubids.edu.gh.com 23
Non-Linear Data Structure
❖ Non-linear data structure is a type of data structure in which
data elements are not arranged in a sequential order, and each
element may have one or more predecessors and successors.
2. Examples include arrays, linked lists, 2. Examples include trees and graphs.
stacks, and queues.
3. Linear data structures have a simple 3. Non-linear data structures have a
organizational structure. more complex organizational structure.
www.ubids.edu.gh.com 27
STATIC AND DYNAMIC DATA STRUCTURES
• A static data structure refers to a data structure with a fixed size
that is determined at compile time and cannot be altered during
program execution.
www.ubids.edu.gh.com 29
Point to note:
• It's important to note the difference between static and
dynamic data structures and static and dynamic typing .
Static and dynamic data structures refer to the management of
memory and data organization, while static and dynamic
typing refer to how data types are handled in a programming
language.
• Example of Statically typed programming languages are C ,
C++,Java, and Swift
• Example of Dynamically typed Programing languages are Python,
PHP, JavaScript, and Ruby.
www.ubids.edu.gh.com 30
DIFFERENCE BETWEEN DATA TYPE AND
DATA STRUCTURE
DATA TYPE DATA STRUCTURE
✓ Data type holds a single ✓ Data structure is a collection
value of a particular type of different kinds of data.
www.ubids.edu.gh.com 31
DIFFERENCE BETWEEN DATA TYPE AND DATA
STRUCTURE
DATA TYPE DATA STRUCTURE
✓ There is no time complexity ✓ In data structures time
in the case of data type complexity plays a important
role.
✓ Implementation is easier ✓ Implementation is relatively
difficult.
www.ubids.edu.gh.com 32
Algorithms
•Algorithms are sequence of steps performed
on the data using efficient data structure to
solve a given problem.
www.ubids.edu.gh.com 33
DATA STRUCTURES OPERATIONS
• Data structures support various operations that allow
for efficient manipulation and retrieval of data.
www.ubids.edu.gh.com 35
Searching Operation
• Searching operations involve finding the location or
existence of a specific element within a data structure.
www.ubids.edu.gh.com 38
Insertion operation
• The insertion operation involves adding a new element
to a data structure.
www.ubids.edu.gh.com 39
Update/Modification:
• This operation involves modifying the value of an
existing element within a data structure.
• Fixed Size: Arrays have a fixed size that is determined at the time of
declaration. The size remains constant throughout the lifetime of the array,
and it cannot be dynamically changed without creating a new array.
• Homogeneous Elements: Arrays store elements of the same data type. All
elements in an array have the same size, allowing for efficient memory
allocation and access.
www.ubids.edu.gh.com 43
Characteristics of Arrays
• Indexing: Arrays use zero-based indexing, where the first
element is accessed using the index 0, the second element
with index 1, and so on. The index allows for quick and
direct access to any element within the array.
www.ubids.edu.gh.com 46
Real World Applications of Arrys
• Databases: Databases often use arrays to store and organize data efficiently.
For example, an array can be used to store a list of customer names, product
information, or employee details. Arrays allow for quick retrieval and
manipulation of data in database management systems.
www.ubids.edu.gh.com 47
Real World Applications of Arrays
• Image and signal processing: Arrays are crucial in image and signal
processing applications. Images and signals are represented as
multidimensional arrays, where each element corresponds to a pixel or a
data point. Arrays enable manipulation of images and signals through
operations like filtering, noise removal, compression, and feature
extraction. www.ubids.edu.gh.com 48
Real World Applications of Arrays
www.ubids.edu.gh.com 49
Types of Arrays
1. One-Dimensional Arrays: One-dimensional arrays, also
known as vectors or lists, store elements in a linear sequence.
Elements are accessed using a single index. For example, an
array of integers [3, 7, 2, 9, 5] is a one-dimensional array.
2. Multi-Dimensional Arrays: Multi-dimensional arrays
organize elements in multiple dimensions, such as rows and
columns or higher-dimensional arrangements. Common
examples include matrices, which are two-dimensional arrays,
and cubes, which are three-dimensional arrays.
3. Static Arrays: Static arrays have a fixed size defined at the
time of their declaration and cannot be resized during runtime.
The size of a static array is typically determined explicitly,
such as int [5] representing an array of five integers.
www.ubids.edu.gh.com 50
Types of Arrays
1. Dynamic Arrays: Dynamic arrays, also known as resizable
arrays or vectors, allow the size to be dynamically adjusted
during runtime. Dynamic arrays are particularly useful when the
number of elements is unknown or may change. Programming
languages may provide dynamic array implementations or
resizable data structures like ArrayList in Java or vectors in C++.
2. Jagged Arrays: Jagged arrays, also called ragged arrays, are
multi-dimensional arrays where each row can have a different
length. In contrast to regular multi-dimensional arrays with fixed
row and column sizes, jagged arrays provide flexibility in
accommodating varying row lengths.
3. String Arrays: String arrays store a collection of strings, where
each element is a string data type. They are commonly used to
hold lists of names, words, or any textual information.
www.ubids.edu.gh.com 51
Implementation of Arrays
• Declaration of Arrays:
type arrayName[arrySize];
www.ubids.edu.gh.com 52
Implementation of Arrays
www.ubids.edu.gh.com
53
Practice
• Declare an array of any size with different types (int, float, string,
double etc)
• Initialize the elements
• Access each element and print out
• Print out all elements
www.ubids.edu.gh.com 54
Implementation of Arrays
Taking Inputs
from User
www.ubids.edu.gh.com 55
Max and Min Value in Arrays
www.ubids.edu.gh.com 56
www.ubids.edu.gh.com 57
Algorithms
Algorithm refers to a well-defined set of instructions
or a step-by-step procedure for performing specific
operations on data structures.
www.ubids.edu.gh.com 58
Steps in writing and an Algorithm
• Understand the problem: Begin by thoroughly understanding the problem
or task you need to solve. Clarify the requirements, constraints, and expected
input-output behavior.
• Identify the inputs and outputs: Determine the input values or data required
by the algorithm, as well as the expected output or result.
• Break down the problem: Break down the problem into smaller,
manageable subtasks or steps. Identify the key operations or decisions needed
to solve the problem.
• Define the logical flow: Determine the logical flow of the algorithm. Use
constructs like conditionals (if-else statements), loops, and function calls to
control the flow and handle different cases.
www.ubids.edu.gh.com 59
• Write the steps in pseudocode: Express the algorithm steps in
pseudocode, which is a high-level, human-readable description of the
algorithm using plain language. Pseudocode should be clear, concise,
and independent of any specific programming language.
www.ubids.edu.gh.com 60
• Test and debug: Test the algorithm implementation with various test
cases, including typical inputs, edge cases, and boundary values.
Verify that the algorithm produces the expected outputs. If any issues
arise, debug and fix the algorithm accordingly.
www.ubids.edu.gh.com 61
Sorting Algorithms for Arrays
www.ubids.edu.gh.com 62
Sorting Algorithm
•A sorting algorithm is a procedure or a set of
steps that arranges elements in a specific order.
www.ubids.edu.gh.com 63
•Sorting algorithms vary in their approach,
complexity, and efficiency. Some algorithms
compare pairs of elements and swap them if
they are out of order, while others divide the
input into smaller subproblems and recursively
sort them.
www.ubids.edu.gh.com 67
Bubble Sort
www.ubids.edu.gh.com 68
Implementation in C++
www.ubids.edu.gh.com 69
Selection Sort
✓Selection sort finds the minimum element from the
unsorted part of the array and swaps it with the element
at the beginning of the unsorted part.
www.ubids.edu.gh.com 70
Selection Sort:
www.ubids.edu.gh.com 71
Algorithm for Selection sort
www.ubids.edu.gh.com 72
www.ubids.edu.gh.com 73
Quick Sort
• Quick sort uses a divide-and-conquer strategy by
selecting a pivot element and partitioning the array into
two sub-arrays, one containing elements smaller than the
pivot and the other containing elements greater than the
pivot.
• The process is recursively applied to the sub-arrays until
the entire array is sorted.
• Quick sort has an average time complexity of O(n log n).
• Quicksort is an in-place sorting algorithm, meaning it
does not require additional memory proportional to the
input size. It swaps elements within the array during
partitioning, resulting in lower memory usage.
www.ubids.edu.gh.com 74
Quick Sort
www.ubids.edu.gh.com 75
Merge Sort
•Merge sort is a sorting algorithm that follows
the divide-and-conquer approach.
www.ubids.edu.gh.com 76
Merge Sort
www.ubids.edu.gh.com 77
Search Algorithm
• A search algorithm is a procedure or method used to find
the location, existence, or specific properties of a target
element or value within a given data structure.
www.ubids.edu.gh.com 79
Linear Search Algorithm
• Linear Search ( Array A, Value x)
• Step 1: Set i to 1
• Step 2: if i > n then go to step 7
• Step 3: if A[i] = x then go to step 6
• Step 4: Set i to i + 1
• Step 5: Go to Step 2
• Step 6: Print Element x Found at index i and go to step 8
• Step 7: Print element not found
• Step 8: Exit
www.ubids.edu.gh.com 80
Binary Search
• Binary Search: Binary search is an efficient search
algorithm that can be applied on sorted collections. It
repeatedly divides the search space in half by comparing
the target element with the middle element of the
collection.
www.ubids.edu.gh.com 81
Steps of Binary Search
1. Sort the Array: Ensure that the array is sorted in ascending order.
Binary search requires the array to be sorted for accurate results.
2. Set Search Bounds: Define the lower bound (low) and upper
bound (high) for the search. Initially, set low to 0 (the first index of
the array) and high to the length of the array minus 1 (the last
index).
a. Find the Middle Element: Calculate the middle index (mid) as the
average of low and high (rounded down to the nearest integer).
b. Compare with Target Value: Compare the value at the mid index with the
target value you are searching for.
www.ubids.edu.gh.com 82
Steps of Binary Search
• If the value at mid is equal to the target value, the search is successful, and
you can return mid as the position of the target value.
• If the value at mid is greater than the target value, set high to mid - 1 to search
in the lower half of the array.
• If the value at mid is less than the target value, set low to mid + 1 to search in
the upper half of the array.
4. Repeat the Binary Search: Go back to step 3 and repeat the process
until the target value is found or until low becomes greater than high.
5. Target Value Not Found: If the search exits the loop and low is
greater than high, it means the target value is not present in the array.
6. Return Result: If the target value is found, return the index of the
target value. Otherwise, return an indication that the target value is not
present in the array
www.ubids.edu.gh.com 83
Example of Binary search of Arrays
• Let's consider the sorted array: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
• arr[mid] = arr[4] = 10
www.ubids.edu.gh.com 84
• Since 10 < 12, set low = mid + 1 = 4 + 1 = 5
• Repeat steps 2 and 3:
www.ubids.edu.gh.com 87
• Hashing: Hashing is a technique used to index and search data in
hash tables. It involves mapping the target element to a unique
identifier called a hash value.
• By using the hash value as an index, the search algorithm can directly
access the corresponding element in constant time on average.
However, in the worst case, hashing can have a time complexity of
O(n), where n is the number of elements in the hash table.
• These are just a few examples of search algorithms. The choice of the
most appropriate search algorithm depends on various factors,
including the properties of the data structure, the size of the dataset,
and the specific requirements of the search operation.
www.ubids.edu.gh.com 88
www.ubids.edu.gh.com 89
Linked List
• A linked list is a linear data structure where each
element, known as a node, contains a value and a
reference (or link) to the next node in the sequence.
• Types of Linked list include;
• A singly-linked list is a type of linked list where
each node contains a value and a reference to the
next node in the sequence.
• In a singly linked list, traversal can only be done in
one direction, from the head (the first node) to the
tail (the last node).
www.ubids.edu.gh.com 90
Singly-linked list
www.ubids.edu.gh.com 92
Queue
• A queue is an abstract data type (ADT) that represents a
collection of elements with a specific order.
www.ubids.edu.gh.com 93
Queue
www.ubids.edu.gh.com 94
Key characteristics of a queue
• Enqueue: Adding an element to the queue is called enqueue. The
new element is inserted at the end of the queue, becoming the last
element.
• Front: The front of the queue refers to the element that will be
dequeued next. It represents the earliest added element in the
queue.
• Rear: The rear of the queue refers to the element that was most
recently added. It represents the last element in the queue.
www.ubids.edu.gh.com 95
Key characteristics of a queue contd.
• Empty Queue: If there are no elements in the
queue, it is considered empty, and attempting to
dequeue an element will result in an error or an
empty value.
www.ubids.edu.gh.com 96
Stack
• A stack is an abstract data type (ADT) that represents
a collection of elements with a specific order.
www.ubids.edu.gh.com 98
Characteristics of stacks
• Push: Adding an element to the stack is called push.
The new element is inserted on top of the stack,
becoming the most recently added element.
• Minor Criteria
➢Network Consumption
➢ Power
➢CPU registers
www.ubids.edu.gh.com 104
Common Natation of time Complexity
• Big O notation (O)
➢Big O notation represents the upper bound or worst-case
scenario of an algorithm's time complexity. It provides an
estimation of how the running time grows relative to the input
size. For example, if an algorithm has a time complexity of
O(n), it means the running time grows linearly with the input
size, or if it has a time complexity of O(n^2), it means the
running time grows quadratically with the input size.
•Omega notation (Ω)
➢Omega notation represents the lower bound or best-case
scenario of an algorithm's time complexity. It provides an
estimation of the minimum growth rate of the running time.
For example, if an algorithm has a time complexity of Ω(n), it
means the running time is at least linear, or if it has a time
complexity of Ω(n^2), it means the running time is at least
quadratic. www.ubids.edu.gh.com 105
•Theta notation (Θ)
➢Theta notation represents both the upper and
lower bounds of an algorithm's time complexity. It
provides a tight estimation of the growth rate. For
example, if an algorithm has a time complexity of
Θ(n), it means the running time grows linearly
with the input size, and it neither grows slower
nor faster than that
www.ubids.edu.gh.com 106
Time complexity with Big O
• O(1) - Constant Time: The running time is constant and does
not depend on the input size. Regardless of the input, the
algorithm takes a fixed amount of time to execute.
• O(n) - Linear Time: The running time grows linearly with the
input size. For an algorithm with linear time complexity, the
running time increases proportionally to the size of the input.
www.ubids.edu.gh.com 107
Time complexity notations
• O(n log n) - Linearithmic Time: The running time grows in a
combination of linear and logarithmic growth. This complexity often
arises in efficient sorting algorithms like merge sort or quicksort.
www.ubids.edu.gh.com 108
Time Complexity graph
www.ubids.edu.gh.com 109
Growth rates/Performance of Sort
Algorithms
www.ubids.edu.gh.com 110
Steps for Big-O Analysis
• Identify the input size: Determine what parameter(s) of the
algorithm determine the size of the input. For example, in an
algorithm that sorts an array, the input size is typically the length
of the array.
www.ubids.edu.gh.com 112
Example
•Constant Time Complexity (O(1))
int x = 5;
➢This statement assigns the value 5 to the variable x. It executes in constant
time because it performs a single operation, regardless of the input size.
www.ubids.edu.gh.com 113
Examples
•Quadratic Time Complexity (O(n^2))
➢This nested loop prints all combinations of i and j, where n is the input value.
Since there are two nested loops, the time complexity becomes quadratic,
resulting in O(n^2).
www.ubids.edu.gh.com 114
Example
• Logarithmic Time Complexity (O(log n))
int num = n;
while (num > 1) {
num = num / 2;
}
www.ubids.edu.gh.com 115
Example
• Exponential Time Complexity (O(2^n))
int Fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
}
➢This recursive function calculates the nth Fibonacci number. The
number of recursive calls grows exponentially with the input value n,
resulting in an exponential time complexity.
www.ubids.edu.gh.com 116
Example of Time and Space complexity analysis
with Big-O
def sum_array(arr){
total = 0
for num in arr
total += num
return total
• Time Complexity: O(n)
• Space Complexity: O(1)
www.ubids.edu.gh.com 117
SORTING OF ARRAYS
www.ubids.edu.gh.com 118