Data Structures
and Algorithms
PREPARED BY
PROF. DR . AMANY SARHAN
2024
Types of Data Structures
What is the data
? structure
A data structure can be defined as a particular
scheme of organizing related data items.
The nature of the data items depends on the
problem at hand.
They can range from elementary data types
(e.g., integers or characters) to data structures
(e.g., a one-dimensional array of one-dimensional
arrays is often used for implementing matrices).
The Need for Data Structures
Goal: to organize data
Criteria: to facilitate efficient
1. storage of data
2. retrieval of data
3. manipulation of data
Design Issue:
◦ select and design appropriate data types
(This is the main motivation to learn and understand data structures)
◦ There are a few data structures that have proved to be particularly
important for computer algorithms.
Linear and Complex Data
Structures
The two most important elementary data
structures are the array and the linked list.
We will study also queue, stack, graph and
tree data structures which is higher in
complexity.
Types of Data Structures to study
Array
Linked List
Graph
Tree Queue Stack
Data Structure Operations
Navigating
Accessing each data element exactly once so that certain
items in the data may be processed
Searching
Finding the location of the data element (key) in the
structure
Insertion
Adding a new data element to the structure
Data Structure Operations
Deletion
◦ Removing a data element from the structure
Sorting
◦ Arrange the data elements in a logical order
(ascending/descending)
Merging
◦ Combining data elements from two or more data
structures into one
Important functions on
any data structure
Build (x) => build the data structure
Get length => identify the no of items in DS
Get item => access specific item in DS
Set item => change the value of specific item
in DS
Iterate => navigate through the items in DS
Important functions on
any data structure
For example, if we have items x0, x1, …..,xn-1
Build (x) => create the data structure (array, linked list,…
etc)
Get length => return n (no of items)
Get item => return xi (i is the item index)
Set item => store a value at xi = w
Iterate => output x0, x1, ….., xn-1 in specific order
The most easiest way is to use arrays
Arrays
Arrays
It is a sequence of words placed in contiguous places in
the RAM, even it is multidimentional
An array starts at address x in RAM, for example.
To access the array in position i, this means we access
memory at position x+i.
Array[i] = array[memory address of array + i]
1 0 1 0
0 1 1 0
1 0 0 1
0 1 0 1
Contiguous Storage of
Array in RAM
If the first element of an array starts at memory address a
Each array element occupies b bytes,
Then, the second element starts at a + b , third starts at a
+ 2.b,….
In general, the i th element starts at a + i.b.
In an array that has N elements, it will be located from a
to a + N.b
Access time of Array
Elements
This means we can access each item at a constant time
We will call it O(1) (order of 1, means constant time)
Accessing time to array[h] = Accessing time to array[w]
This is called random accessing of array (as we know about the RAM)
Then get item and set item time is O(1) in arrays.
Building the array, however, is dependent on its size
Then Build (x) time is O(n) in arrays.
If you do not know the size of data, you tend to make large size of array
which you may use a part of it only. This is a waste of time and space!!!!!
Array Dimensions
Arrays are table-like structures. You can also think of them
as matrices in mathematics.
An array's dimension specifies how many indices an array
1 0 1 0
has. 1 0 1 0
0 1 1 0
1.2 1 0 1 0 1 00 11 10 0
1 00 111 100 0 0 1
2.1 0 1 1 0 1 0 0 1
0 11 10 01 0 1
6.5 1 0 0 1 00 10 01 1
1 00 10 01 1
17.0 0 1 0 1
0 1 0 1
1-dimensional 2-dimensional
array array 3-dimensional array
Two Dimensional Array
Representation
We typically represent a matrix or two-dimensional array
by one or more one dimensional arrays.
The two most common ways to store a matrix are:
◦ row-major and column-major order.
◦ Let’s consider an m X n matrix (m rows and n columns.
In row-major order, the matrix is stored row by row,
In column-major order, the matrix is stored column by
column.
Two Dimensional Array
Representation
For example, consider the 2 X 3 matrix
Eq. (10.1)
Row-major order stores the two rows 1 2 3 and 4 5 6,
Column-major order stores the three columns 1 4; 2 5;
and 3 6.
Figure 10.1 shows how to store this matrix using a single
one-dimensional array.
Basic usages of
arrays
Array declaration and creation
Accessing elements in arrays
Array declaration and creation
Each element in an array must be of the same type.
Arrays are declared using the following syntax:
type array-name [no. of items];
Where type is the data type of the array elements.
Here are some examples:
Float names[100];
Char SS[3];
Array Properties
long[
long[ ]] row
row == new
new long[4];
long[4]; row.Rank
row.Rank 11
0 0 0 0 row.Length
row.Length 44
row
int[,]
int[,] grid
grid == new
new int[2,3];
int[2,3];
grid.Rank
grid.Rank 22
0 0 0 grid.Length
grid.Length 66
grid 0 0 0
Methods and Properties for Retrieving Array Metadata
Length: Returns the total number of elements in all
dimensions of an array.
GetLength: Returns the number of elements in
specified dimension of an array.
Rank: Returns the number of dimensions of an array.
GetType: Returns the Type of the current array
instance.
Array Methods
Commonly used methods
◦ Sort – sorts the elements in an array of rank 1
◦ Clear – sets a range of elements to zero or null
◦ Clone – creates a copy of the array
◦ IndexOf – returns the index of the first occurrence
of a value
Array's Length
Each array has a fixed number of slots; they
are numbered from 0, 1, 2, and so on.
We can find out the number of slots an array
has using property Length.
int a[5];
a.Length is 5.
Basic usages of arrays
Array declaration and creation
Accessing elements in arrays
Accessing elements
by indices
You can access elements in an array using their
indices.
Again, the first index is 0. 0 a[0]
0 a[1]
int a[5];
0 a[2]
a 0 a[3]
0 a[4]
Small practice
What is the output of the following program?
int a[3];
a[0] = 5; a[1] = 10; a[2] = 150;
Cout<<a[0]<< a[1]<< a[2]);
a[0] += 5;
a[1] = 20;
a[2] = a[0] + a[1];
Cout <<“The new values”<<a[0]<< a[1]<< a[2]);
5 10 150
10 20 30
Array one-dimensional
array
void Main() {
int sample[10];
int i;
for(i = 0; i < 10; i = i+1) {
sample[i] = i;
}
for(i = 0; i < 10; i = i+1) {
cout<<"sample[" << i<< "]: “<< sample[i];
}
}
}
Declare an integer array
Quiz of 5 elements where the values
of each element is equal to its
index multiplied by 3
(i.e. first element=0, the
second=3,.. etc)
Then print them
Compute the average of a
set of values
void Main() {
int nums[10]; int avg = 0;
nums[0] = 99; nums[1] = 10;
nums[2] = 100; nums[3] = 18;
nums[4] = 78; nums[5] = 23;
nums[6] = 63; nums[7] = 9;
nums[8] = 87; nums[9] = 49;
for(int i=0; i < 10; i++)
avg = avg + nums[i];
avg = avg / 10;
cout<<"Average: “<< avg;
}
Reverse an array into a
second array
void Main() {
int i, j;
int nums1 [10], nums2[10];
for(i=0; i < nums1.Length; i++)
nums1[i] = i; // set the values of first array
cout<<“Original contents: ";
for(i=0; i < nums2.Length; i++)
cout<<nums1[i]<< " "; // print content of first array
// reverse and copy nums1 to nums2
for(i=0, j=nums1.Length-1; i < nums1.Length; i++, j--) {
nums2[j] = nums1[i];
}
cout<<“/n Reversed contents: ";
for(i=0; i < nums2.Length; i++)
cout<<nums2[i]<< " "; // print content of second array
}
Two-Dimensional
Representation
Two-dimensional structure
33
Two-Dimensional Arrays
Declaration format
type identifier[integral value, integral value];
Two integral values are required for a two-dimensional
array
Number of rows is listed first
Data values placed in array must be of the same base
type
Example (create a 7x3 matrix)
◦ int calories [7, 3];
34
Two-Dimensional Arrays
(continued)
calories
reference
s address
of
calories[
0,0]
Two-dimensional calories array
35
Two-Dimensional Arrays
(continued)
Length property gets total number of elements in all
dimensions
Cout<<calories.Length; // Returns 21
GetLength( ) – returns the number of rows or columns
◦ GetLength(0) returns number of rows
◦ GetLength(1) returns number of columns
Cout<< calories.GetLength(1); //Display 3 (columns)
Cout<< calories.GetLength(0); //Display 7 (rows)
Cout<< calories.Rank; // returns 2 (dimensions)
36
Multi Dimensional Arrays
void Main()
{
const int rows = 4, columns = 3; // declare a 4x3 integer array
int rectangularArray[rows, columns];
for (int i = 0;i < rows;i++)
{
for (int j = 0;j<columns;j++)
{
rectangularArray[i,j] = I + j;
}
}
for (int i = 0;i < rows;i++)
{
for (int j = 0;j<columns;j++)
{
cout<<"rectangularArray[{0},{1}] = {2}", i, j, rectangularArray[i,j]);
}
}
}
How to write a general
?algorithm
?What is algorithm
A finite set of instructions which accomplish a
particular task
A method or process to solve a problem
Transforms input of a problem to output
Algorithm = input + process + output
Algorithm development is an art – it needs
practice, practice and only practice!
?What is a good algorithm
It must be correct
It must be finite (in terms of time and size)
It must terminate
It must be unambiguous
Which step is next?
It must be space and time efficient
A program is an instance of an algorithm, written in some
specific programming language
A simple algorithm
Problem: Find maximum of a, b, c
Algorithm
Input = a, b, c
Output = max
Process
o Let max = a
o If b > max then
◦ max = b
o If c > max then
◦ max = c
o Display max Order is very important!!!
Algorithm development: Basics
Clearly identify:
what output is required?
what is the input?
What steps are required to transform input into output
o The most crucial bit
o Needs problem solving skills
o A problem can be solved in many different ways
o Which solution, amongst the different possible solutions is optimal?
?How to express an algorithm
A sequence of steps to solve a problem
We need a way to express this sequence of steps
1. Natural language (NL) is an obvious choice, but not a good
choice. Why?
o NLs are notoriously ambiguous (unclear)
2. Programming language (PL) is another choice, but again not a
good choice. Why?
o Algorithm should be PL independent
We need some balance
o We need PL independence
o We need clarity
o Pseudo-code provides the right balance
?What is Pseudo-code
Pseudo-code is a short hand way of describing a
computer program
Rather than using the specific syntax of a computer
language, more general wording is used
It is a mixture of NL and PL expressions, in a
systematic way
Using pseudo-code, it is easier for a non-programmer to
understand the general workings of the program
Pseudo-code: General Guidelines
Use PLs construct that are consistent with
modern high level languages, e.g. C++, Java, ...
Use appropriate comments for clarity
Be simple and precise
Components of Pseudo-code
Expressions
Standard mathematical symbols are used
o Left arrow sign (←) as the assignment operator in assignment
statements (equivalent to the = operator in Java)
o Equal sign (=) as the equality relation in Boolean expressions
(equivalent to the "= =" relation in Java)
o For example
Sum ← 0
Sum ← Sum + 5
What is the final value of sum?
Components of Pseudo-code (cont.)
Decision structures (if-then-else logic)
if condition then
true-actions
[else
false-actions]
We use indentation to indicate what actions should
be included in the true-actions and false-actions
For example
if marks > 50 then
print “Congratulation, you are passed!”
else
print “Sorry, you are failed!”
end if
Components of Pseudo-code (cont.)
Loops (Repetition)
◦ Pre-condition loops
o While loops
◦ while condition do actions
◦ We use indentation to indicate what actions should be
included in the loop actions
◦ For example
while counter < 5 do
print “Welcome to data structure course!”
counter ← counter + 1
end while
What will be the output if counter is initialised to 0, 7?
Components of Pseudo-code (cont.)
Loops (Repetition)
◦ Pre-condition loops
o For loops
◦ for variable-increment-definition do actions
◦ For example
for counter ← 0; counter < 5; counter ← counter + 2
do
print “Welcome to data structure course!”
end for
What will be the output?
Components of Pseudo-code (cont.)
Loops (Repetition)
Post-condition loops
o Do loops
◦ do actions while condition
◦ For example
do
print “Welcome to CS204!”
counter ← counter + 1
while counter < 5
What will be the output, if counter was initialised to 10?
The body of a post-condition loop must execute at least once
Components of Pseudo-code (cont.)
Method declarations
◦ Return_type method_name (parameter_list) method_body
◦ For example
integer sum ( integer num1, integer num2)
start
result ← num1 + num2
end
Method calls
object.method (args)
For example
mycalculator.sum(num1, num2)
Components of Pseudo-code (cont.)
Method returns
return value
For example
integer sum ( integer num1, integer num2)
start
result ← num1 + num2
return result
end
Components of Pseudo-code (cont.)
Arrays
A[i] represents the i th cell in the array A.
The cells of an n-celled array A are indexed from
A[0] to A[n − 1]
Algorithm Design: Practice
Example 1: Determining even/odd number
A number divisible by 2 is considered an even number,
while a number which is not divisible by 2 is considered an
odd number. Write pseudo-code to display first N odd/even
numbers.
Example 2: Computing Weekly Wages
Gross pay depends on the pay rate and the number of hours
worked per week. However, if you work more than 40 hours,
you get paid time-and-a-half for all hours worked over 40.
Write the pseudo-code to compute gross pay given pay rate
and hours worked
Even/ Odd Numbers
Input range
for num←0; num<=range; num←num+1 do
if num % 2 = 0 then
print num is even
else
print num is odd
endif
endfor
Computing weekly wages
Input hours_worked, pay_rate
if hours_worked <= 40 then
gross_pay ← pay_rate x hours_worked
else
basic_pay
← pay_rate x 40
over_time ← hours_worked – 40
over_time_pay ← 1.5 x pay_rate x over_time
gross_pay ← basic_pay + over_time_pay
endfor
print gross_pay
1. Write an algorithm to find the
largest of a set of numbers.
Homework You do not know the number
of numbers.
2. Write an algorithm in
pseudocode that finds the
average of (n) numbers.
For example numbers are
[4,5,14,20,3,6]s
#Examples in C
Instantiate the array -2
A second line is necessary to (since it is an object
of System.Array type) and to determine the size of
the array.
names = new string[10];
You can combine these two statements into one
line when necessary to do
string[] names = new string[10];
.Instantiate the array Cont -2
There are times when you will want to declare,
instantiate, and assign data to an array in one
statement. You can do this in C# using an
initialization list:
int[] numbers = new int[] {1,2,3,4,5};
Direct access
Direct access involves referencing an array position
by index on the left-hand side of an assignment
statement:
Names[2] = "Raymond";
Sales[19] = 23123;
myName = names[2];
Set the value of an array element
To set the value of an array element. The
method takes two arguments,
an index number and the value of the element.
names.SetValue[2, "Raymond"];
sales.SetValue[19, 23123];
illustrates how to initialize
arrays
void Main() {
int intArray[5] = {10, 20, 30, 40, 50};
for (int counter = 0; counter < intArray.Length; counter++)
{
Console.WriteLine("intArray[" + counter + "] = " + intArray[counter]);
}
// char arrays
char[] charArray = new char[] {'h', 'e', 'l', 'l', 'o'};
for (int counter = 0; counter < charArray.Length; counter++)
{
Console.WriteLine("charArray[" + counter + "] = " + charArray[counter]);
}
// string arrays
string[] stringArray = {"Hello", "World"};
foreach (string myString in stringArray)
{
Console.WriteLine("myString = " + myString);
}
}
}
Comparing Strings
String Contains String
gets last array element
for-loops on array
uses foreach, array
for-loops on array
Join and Split String Array
loops over 2D string array
?How can I test if an array contains a certain value
string[] week = new string[7];
week[0] = "Sunday";
week[1] = "Monday";
week[2] = "Tuesday";
week[3] = "Wednsday";
week[4] = "Thursday";
week[5] = "friday";
week[6] = "Saturday";
string value = "Wednsday";
int pos = Array.IndexOf(week, value);
if (pos > -1)
MessageBox.Show(value + " exist !");
else
MessageBox.Show(value + " not exist !");
Sorting Arrays
72
Multidimensional Arrays
int[,] grades = new int[4,5];
declares a two-dimensional array,