Lecture 1 to Lecture 8 Theory Lecturer Kanar Shukr Muhamad Data Structure and Algorithm Design 2019-2020 University of Salahaddin-Hawler College of Engineering Software and Informatics Engineering Department First Year Class
Lecture 1 to Lecture 8
Theory
Lecturer
Kanar Shukr Muhamad
Data Structure
and
Algorithm Design
2019-2020
University of Salahaddin-HawlerCollege of EngineeringSoftware and Informatics Engineering DepartmentFirst Year Class
Lecture 1
Lecturer
Kanar Shukr Muhamad
Data Structure
and
Algorithm Design
2019-2020
University of Salahaddin-HawlerCollege of EngineeringSoftware and Informatics Engineering DepartmentFirst Year Class
Objectives
3
The students in this course will learn how the data structures are
built
The course, intended to clarify the concepts used to build data inside
computer and how different searching and sorting techniques are
applied to it.
Finally, the student will be introduced to different techniques of
building algorithms.
Syllabus
4
The following topics will be covered:
o Introduction to the course and data
structure concepts and mechanisms
o Asymptotic Complexity
o Abstract Data Type Stack
Queue
Linked List
o Pointer and heap memory.
o Tree Data Structure
o Sorting Algorithms
oSearching Algorithms
oGraph Theory and its
algorithms
References
5
Data Structurs, Algorithms and Application in C++ by S. Sahni,
any edition
Data Structure and Programming Design in C++ by Krurse and
Ryba, Prentice Hall, any edition.
Algorithms and Data Structures by Kurt Mehlhorn and Peter
Sanders, any edition.
Advanced Data Structures by Prof. Erik Demaine, Notes
Collection.
Fundamentals of Data Structures by Ellis Horowitz and Sartaj
Sahni
Course Overview
6
Introduction to many of the basic data structures used in computer
software
Understand the data structures
Analyze the algorithms that use them
Know when to apply them
Practice design and analysis of data structures.
Practice using these data structures by writing programs.
Goals
7
You will understand
what the tools are for storing and processing common data types
which tools are appropriate for which
So that you will be able to
Justify your design decisions via formal reasoning
Communicate ideas about programs clearly and precisely
Terminology
8
Abstract Data Type (ADT)
Mathematical description of an object with set of operations on the
object. Like stack, queue,…
Data Type
A data type is a well-defined collection of data with a well-defined
set of operations on it.
Data Types versus Data Structure
9
Algorithm
A high level, language independent, description of a step-by-step
process
Data structure
A specific family of algorithms for implementing an abstract data
type.
Implementation of data structure
A specific implementation in a specific language
Data Structure
10
A data structure is a logical representation to understand physical
representation.
“Clever” ways to organize information in order to enable efficient
computation
A data structure is a particular way of storing and organizing data in
a computer so that it can be used efficiently.
Data Structure Continue
11
Data structures organize data
more efficient programs.
More powerful computers
more complex applications.
More complex applications demand more calculations.
Complex computing tasks are unlike our everyday experience.
Data Structure Features
12
Ideal data structure:
“fast”, “elegant”, memory efficient
Generates tensions:
time vs. space
performance vs. elegance
generality vs. simplicity
one operation‟s performance vs. another‟s
Organizing Data
13
Any organization for a collection of records can be searched,
processed in any order, or modified.
The choice of data structure and algorithm can make the difference
between a program running in a few seconds or many days.
Efficiency
14
A solution is said to be efficient if it solves the problem within its
resource constraints.
Space
Time
The cost of a solution is the amount of resources that the solution
consumes.
Introduction to C++ Programming Language
15
To be able to write effective programs, one needs to know a few
things:
Mastery of the tools-of-the-trade (programming language,
development environment etc.)
The ability to analyze a “real world” problem and to construct a
model for it suitable for programming.
Careful design of an algorithm and user-interface for the program
at hand.
Knowing the techniques that have made other programmers more
effective.
Variables
16
A variable is a placeholder used for storing data.
The type of data may be numerical, string, character and any other type that the
language supports
The data in a variable is called its value and it can be changed or deleted.
In order to uniquely identify and keep track of a variable, we need to give each
variable a name; this is called declaring a variable.
For example: int books; double myWeight;
The books variable is declared of type integer, and the variable myWeight is of
type double, its value can be a number with a fraction like 1.3. declaration
statements end with simi colon)
Assignment Statements
17
Values can be assigned or stored in variables with assignment statements:
books=34;
An assignment statement is an order, to the computer, to assign the value on
the right-hand side of the equal sign to the variable on the left-hand side. The
sign (=) is called the assignment operator. (Assignment statements end with a
semicolon.)
The value on the right-hand side can also be another variable or expression:
books1=books2;
In an assignment statement, first the value on the right-hand side is evaluated
and then its result is stored or assigned to the variable on the left-hand side.
Performing Output
18
The values of variables, numerical values and strings of text, maybe output to the
screen using cout as in:
int books=0;
cout<<books<<endl;
cout<<72<<endl;
cout<<“This is the output”<<endl;
In the first output statement, the value of variable books will be output on the
screen, which is 0; In the second, the numerical value 72 will be output to the
screen, and in the last statement, the string “This is the output” will be output to
the screen.
Performing Output Continue
19
Typically, you would want a newline to appear after some output to the screen; to
force a newline the C++ keyword endl is appended at the end of the line. A second
method for forcing a newline is using the escape character \n as in:
cout<<“Hello everyone \n”;
But this is only possible when the output is a text of string.
You can also combine a number of outputs in a single output statement as in
cout<<“iam“<<18<<“yearsold”<<endl;
To force a blank line on the screen use either
cout<<endl; or cout<<“\n”;
The double arrow signs (<<) are called the insertion operators.
Lecture 2
Lecturer
Kanar Shukr Muhamad
Data Structure
and
Algorithm Design
2019-2020
University of Salahaddin-HawlerCollege of EngineeringSoftware and Informatics Engineering DepartmentFirst Year Class
Performing Input
21
In C++, cin is used to input values into variables.
int price;
cout<<“Enter the price:”;
cin>>price;
cout<<“The price you entered is $“<<price<<endl;
In this program extract, first an integer is declared, then the user is asked to
enter / type a value for price. This value is then input in the variable price
using cin. A message is also output to the screen notifying the user of the
input value.
Performing Input Continue
22
To have more than one input value entered at the keyboard:
int price1, price2; //(two variables of type int)
cout<<“Enter two prices:”<<endl;
cin>>price1>>price2;
Or you could have two separate cin statements. After each input, the
computer waits for user to input some value. Then the user must type a
space or a tab or a newline to separate the two input values.
A cin statement sets the value of a variable equal to values typed at the
keyboard.
Basic Data Types Continue
23
Notice that character values are placed inside single quotes. While the string data
type where the string of text is placed inside double quotes as in:
char a;
cin>>a;
cout<<“Ths is a character value :”<<a<<“\n While
this is string of text.”<<endl;
So, in C++ the character „A‟ is treated differently from “A” since the first is
considered a character and the second a string.
Values of type bool are called boolean expressions and include only two values:
true or false. Boolean expressions are used in branching and looping statement
Simple C++ Program
24
E.x1: we will write our first complete C++ program.
1.#include<iostream>
using namespace std;
2.int main()
3. {
4. int hours=0;
5. cout<<“How many hours/ week do you practice C++?”;
6. cin>>hours;
7. cout<<“You practice“<<hours<<“per week.”<<endl;
8. return 0;
9. }
Simple C++ Program Continue
25
Line 1:
This include statement directs the C++ compiler to include the
iostream.h library file with the program. This library contains
input/ouput function definitions of the C++ language cin and cout.
Line 2:
Every C++ program must have a function called main. This function has
a body consisting of program statements to be executed in sequence by
the computer.
Simple C++ Program Continue
26
Lines 3, 9:
Every main function starts with an open bracket { and ends with a
close bracket }.
Line 4:
in this line we declare and initialize a variable of type int.
Lines 5:
Here, we are just outputting some text to the screen.
Line 6:
We capture the user input value and store it in a variable.
Simple C++ Program Continue
27
Line7:
In this line, we output some text and at he value of the variable hours.
Line8:
Here, at the end of the program, were turn control to the operating
system and declare that the program has finished its execution.
Important Note
The important thing to remember is that all C++ programs must have
a function called main and that program execution begins and ends
inside this method.
Arithmetic Operator
28
The main C++ arithmetic operator are the following:
+ for addition
- for subtraction
* for multiplication
/ for division
% for division with remainder
Arithmetic Operator Continue
29
Division Operator (/)
If both operands are of type int, the result is of type int. If one, or both operands
are of type double, the result will be of type double.
Remainder Operator(%)
The % operator can be used with operands of type int to recover the information
lost when you use / to do division with operands of type int; for example:
cout<<“11 divided by 3 is “<<11/3<<endl;
cout<<“with a remainder of “<<11%3<<endl;
Output:??????
Precedence Rules
30
You can specify the order of operations in C++ using parentheses as illustrated in
the following expressions:
1: (x+y)*z; the computer first adds x to y and then multiplies the result by z.
2: x+(y*z); the computer first multiplies y by z and then adds the result to x.
If you omit the parentheses, the computer will follow the C++ rules of precedence.
So, if you wrote x+y*z, the computer would multiply y by z and add the result to
x. Because * has higher precedence than +. (the same is true for / and %)
Constants
31
Constants in a C++ program is as follows:
const int ENGINEERING_AVERAGE=90;
if (student_grade>= ENGINEERING_AVERAGE)
cout<<“Engineering Student”<<endl;
else
cout<<“Science Student”<<endl;
This could be a large program and there could be many places where the
constant engineering_average is used. To change eng.average for next year, we
only need to change the value at one place. It‟s common to use capital letters
for constants.
If-Else Statements
32
The general form of the C++ if-else-statement is as follows:
if(Boolean-expression)
yes-statement
else
no-statement
When program execution reaches the if-else-statement only one of the two
statements is executed .If the Boolean-expression is true then the yes-
statement is executed, if the Boolean-expression is false then the no-statement
is executed.
If-Else Statements Continue
33
The table below is the full list of comparison operators in C++:
If-Else Statements Continue
34
E.x2: Suppose your program asks the user about the amount of time per week he/
she spends on practicing C++. And you want the program to decide whether or not
this is enough. Assume that 4hours/week of practice is enough. Any thing less is
not good enough.
#include <iostream.h>
main()
{
int hours_per_week=0;
cout<<“How many hours/week do you practice C++?”;
cin>> hours_per_week;
if (hours_per_week>=4)
cout<<“That‟s good ”<<endl;
else
cout<<“That‟s not good enough”<<endl;
return 0;
{
If-Else Statements Continue
35
You may want to execute more than one statement inside an if-else statement.
To do this, enclose the statements inside brackets { }. For example:
if (grade >=50)
{
cout<<“ The student has passed”<<endl;
passed-students +=1;
}
else
{
cout<<“Student has failed”<<endl;
failed-students +=1;
}
A list of statements enclosed inside brackets is called a compound statement.
If Statements
36
The C++ if-statement like Java if-statement test a condition and if the condition is
satisfied the program does something, otherwise it does not do anything.
You can do this by omitting the else part from the if-else-statement. For example:
if (grade>=50)
cout<<“The student has passed.”<<endl;
cout<<“……”<<endl;
So, if the Boolean expression is not satisfied, the cout statement will not be
executed and program execution will go to the second cout line.
Nesting If-Else Statements
37
by nesting if-else statements, you have a three- or four-way branch so that your
program can choose between more than two alternative actions.
E.x3/ Suppose we want to write a game-playing program in which the user
must guess the value of some number.
cout<<“Guess the number: “;
cin>>guess;
if (guess >50)
cout<<“No, too high”;
else if (guess==50)
cout<<“Correct!”<<endl;
else
cout<<“No, too low”<<endl;
Lecture 3
Lecturer
Kanar Shukr Muhamad
Data Structure
and
Algorithm Design
2019-2020
University of Salahaddin-HawlerCollege of EngineeringSoftware and Informatics Engineering DepartmentFirstYear Class
Loops
39
C++ has a number of ways to create loops. One of them is called a (1-while-
statement or while-loop).
E.x:
#include <iostream.h>
main()
{
int num_of_greetings=0;
cout<<“How many greetings do you want?”;
cin>>num_of_greetings;
while (num_of_greetings> 0)
{
cout<<“Hello “;
num_of_greetings=num_of_greetings-1;
}
return 0;
}
Loops Continue
40
The section between the brackets { and } is called the body of the while-loop.
It is the action that is repeated a number of times. Each repetition of the loop
is called an iteration of the loop.
If the user enters 0 at the keyboard, the loop body is executed zero times, that
is, it is not executed at all. Because, the Boolean-exp is not satisfied and
program execution proceeds with the following line after the while-loop.
You should be sure that the loop ends at some point. Otherwise, the loop will
run forever. In this example, we decrease a variable value after each iteration.
We decrease it by one after each iteration. This is called decrementing.
Loops Continue
41
2-The do-while loop statement is similar to the while-loop statement, except that
the loop body is executed at least once. The syntax of do-while loop statements is
as follows:
do
{
Statement_1;
Statement_2;
…
Statement_n;
} while (Boolean-expression);
Loop body is executed once first, then the Boolean expression is checked for
additional iterations of the loop body.
Loops Continue
42
E.x6/ An example involving a do-while loop statement:
#include <iostream.h>
main()
{
int num_of_greetings=0;
cout<<“How many greetings do you want?”;
cin>>num_of_greetings;
do
{
cout<<“Hello “;
num_of_greetings=num_of_greetings-1;
} while (num_of_greetings> 0)
return 0;
}
Loops Continue
43
3-For Loop
In performing numerical calculations, it is common to do a calculation with the
number one, then with the number two and so forth until some last value is
reached.
For example to add one through ten you want the computer to perform the
following statement ten times with the value of n equal to1 the first time and with
n increased by one each subsequent time.
sum=sum+n
Loops Continue
44
The following is one way to accomplish this with a while statement:
sum=0;
n=1;
while (n<=10)
{
sum=sum + n;
n++;
}
Although awhile-loop is OK here, this kind of situation is just what the for-loop
was designed for. The following for-loop will neatly accomplish the same thing:
sum=0;
for ( n=1; n <= 10; n++)
sum=sum + n;
E.x9/ Write a program to sum the numbers from 1 to 10.
Increment and Decrement Operators
45
The C++ language has two more unary operators ++ and --. The ++ operator is
called the increment operator and – the decrement operator. They are usually use
in variables of type int. The operator ++ increases a variable‟s value by one and –
decreases a variable value by one.
int count=5;
count++;
cout<<“Count is changed to“<<count<<endl;
count--;
cout<<“Count is changed to“<<count<<endl;
Functions and Procedural Abstraction
46
A natural way to solve large problems is to break them down into a series
of smaller sub-problems, which can be solved more-or-less independently
sub-programs and then combined to arrive at a complete solution; in C++
sub-programs are called functions.
There are pre-defined functions that we can use in our programs; we even
don‟t need to know how the are defined as long as we know how to use
them.
You can have user-defined functions too. You can define your own
functions to do specific tasks.
Functions Continue
47
E.x11/Write a function to return area of a rectangle, test your function in a
complete C++ program
#include <iostream.h>
int area(intlength, intwidth);//function declaration
main()
{
int this_length, this_width, rectangle_area;
cout<<“Enter the length followed by width:”;
cin>>this_length>>this_width;
//function call
rectangle_area=area(this_length, this_width);
Functions Continue
48
cout<<“The rectangle area is“<<rectangle_area<<endl;
return 0;
}
int area(intlength, intwidth)//start of function definition
{
int number;
number= length * width;
return number;//function returning a value
}
Void Function
49
In C++ a function that returns no value is called a void function.
E.x/
void myFunction(int num);
main()
{
int x=0;
myFunction(x); //function call
retrun 0;
}
void myFunction(int num)
{
num++;
cout<<“ one plus your number is “<<num<<endl;
}
Array
50
In C++ the array elements are stored in contiguous memory locations. The lowest
address refers to the first element and the highest address refers to the last element.
For example, to store a list of exam marks for students we can use an array as in:
int mark[5];
This array is of type integer and it can hold 5 variables of type integer. Mark is the
name of this array.
Array elements are numbered from 0. That is, the index of the first Element in the
array is 0 and the index of the last element is one less than the size of the array. ( in
this example, first element has index 0 and last element has index 4)
Array Continue
51
You can initialize arrays in this way:
int mark[5]={87,67,90,89,100};
int mark[]={87,67,90,89,100};
To access array elements we use the array name plus the index of the required
element.
Array Continue
52
E.x/Write a C++ program to output the numbers from 1 to 5.
#include <iostream.h>
main()
{
int number[5];
for (int i=0; i<5; i++)
{
number[i]=i;//initialize the array
cout<<i;
cout<<"\t"<<(number[i] * number[i])<<endl;
}
return 0;
}
Array Continue
53
To calculate the address of any element of one dimensional array we use this
syntax:
Location (A[i]) = Base address + (i*size)
i: is address of the current element.
size: is the size of the array type.
Ex.17/ If base address=800, calculate the address of(short A[2])?
Location (A[2]) = BA + i*sizeof(A[2])
So:
Location (A[2]) = 800 + 2*2
=804
Two Dimensional Array
54
In C++ arrays of arrays are called multi dimensional arrays.
The most common form of a multidimensional array is a two-dimensional array
which is similar to a rectangular structure divided in to rows and columns. This
type of two-dimensional array is called a matrix.
Consider the two-dimensional array matrix:
int matrix[2][3]={{2,2,2}, //two rows, three columns
{2,2,2}
This is an array(size2) of two arrays(size3). So the size of this two dimensional
array is 2*3 which is equal to 6.
Two Dimensional Array Continue
55
E.x/ Write a C++ program to add 2 matrixes using a function.
main()
{
int array1[4][2]={ {0,1}, {0,1}, {0,1}, {0,1}};
int array2[4][2]={ {1,1}, {1,1},{2,2},{2,2}};
addMatrixes(array1, array2);
for(i=0; i<4; i++)
{
for(j=0; j<2; j++)
cout<<array1[i][j]<<" ";
}
return 0;
}
Two Dimensional Array Continue
56
void addMatrixes(int a[][2],int b[][2])
{
for(int i=0; i<4; i++)
{
for(intj=0; j<2; j++)
a[i][j]=a[i][j]+ b[i][j];//adding
}// to display the result on the screen
}
Two Dimensional Array Continue
57
Multi-dimensional arrays are mainly used to perform matrix operations and
numerical analysis calculations, you can do all matrix operations like matrix
addition, multiplication, matrix transformations using two-dimensional arrays.
The base type of a multi-dimensional array can be any type; but for numerical
calculations the type is usually int or double..
Lecture 4
Lecturer
Kanar Shukr Muhamad
Data Structure
and
Algorithm Design
2019-2020
University of Salahaddin-HawlerCollege of EngineeringSoftware and Informatics Engineering DepartmentFirst Year Class
Two Dimensional Array Continue
59
To calculate the address in two dimensional array there are two methods:
1.Row-wisemethod.
2.Column-wisemethod.
In row-wise method can arrive to any location of array in memory through rows
until arrive to row that is contain the location of element.
While in column-wise method can arrive to any location of array in memory
through columns until arrive to column that is contain the location of element.
Two Dimensional Array Continue
60
Row-wise method: char a[r][c];
Locationa[i][j]=BA+(i*c+j)*size
Where:
i: is the current row.
c: is total no. of columns.
j: is current column.
size: is the size of the array type.
E.x17: short a[3][4]; BA=400, Find the location of a[0][0] and location a[1][1]?
Location a[0][0]=400+(0*4+0)*2
=400
Locationa[1][1]=400+(1*4+1)*2
=410
Two Dimensional Array Continue
61
Column-wise method: char a[r][c];
Location a[i][j]=BA+(j*r+i)*size
Where:
i: is the current row.
r: is total no. of row.
j: is current column.
size: is the size of the array type.
E.x18/ short a[3][4]; BA=400, Find the location of a[1][1]?
Location a[1][1]=400+(1*3+1)*2
=408
Structure
62
In C++ composite data types are declared using structures.
For example, you can represent a point as a data type whose type is a structure
consisting of two values of type int.
struct point
{
int x;
int y;
};
Structure Continue
63
To declare a variable of this new type, you follow the same method as we did for
basic data types:
point firstPoint;
The variables inside the structure are called member variables and their values the
structure‟s member values.
Member variables are specified by giving the name of the structure variable
followed by a dot and then the member name. For example to initialize the
variable “point” from last slide:
firstPoint.x=0;
firstPoint.y=0;
Structure Continue
64
But it is more common to initialize structures as in:
firstPoint={0,0};
To assign one structure variable to another variable of the same type:
Point firstPoint, secondPoint;
firstPoint={1,2};
secondPoint=firstPoint;
To compare structures with each other:
if(firstPoint==secondPoint) //illegal
if((firstPoint.x==secondPoint.x)
&& (firstPoint.y==secondPoint.y)) //OK
Structure Continue
65
E.x/ Write a C++ program to find distance between any two points using your own
structure:
#include<iostream.h>
#include<math.h>
struct point
{
double x;
int y;
};
Structure Continue
66
main()
{
point firstPoint={4,9};
point secondPoint={5,10};
double distance=0.0;
distance=sqrt(((secondPoint.x–firstPoint.x)*
(secondPoint.x–firstPoint.x))+
((secondPoint.y–firstPoint.y)*
(secondPoint.y–firstPoint.y)))
cout<<“the distance between
points(4,9)and(5,10)is“<<distance<<endl;
return0;
}
Structure Mapping Function
67
The information used to calculate the Structure Mapping Function SMF is the
address of any element in the structure.
1.Data type of each member.
2.Data length of each member.
3.Offset from the base of the structure.
Example:
struct Dept
{
short Room;
char name[10];
float size;
};
Calculate the size of structure.
Structure Mapping Function Continue
68
Structure Mapping Function Continue
69
E.x: Dept B[10]; Base Address=400, find the location of B[3]?
Location(B[i])=Base Address+ size o f structure * i
Location(B[3])=400+16*3
=448
Lecture 5
Lecturer
Kanar Shukr Muhamad
Data Structure
and
Algorithm Design
2019-2020
University of Salahaddin-HawlerCollege of EngineeringSoftware and Informatics Engineering DepartmentFirst Year Class
Asymptotic Complexity
71
Finding the exact complexity, [f(n)= number of basic operations], of an algorithm
is difficult.
This “approximate“ measure of efficiency is called asymptotic complexity.
Thus the asymptotic complexity measure does not give the exact number of
operations of an algorithm, but it shows how that number grows with the size of
the input.
Asymptotic Complexity Continue
72
This gives us a measure that will work for different operating systems, compilers
and CPUs.
The most commonly used notation for specifying asymptotic complexity is the
big-O notation.
Asymptotic Complexity Continue
73
Some Big-O complexity classes in order of magnitude from smallest to highest:
Big-O Examples
74
Rules of big-O
75
For large values of input n, the constants and terms with lower degree of n are
ignored.
Multiplicative Constants Rule: Ignoring constant factors.
O(cf(n))=O(f(n)), where c is a constant;
Example:
O(20n3)=O(n3)
Addition Rule: Ignoring smaller terms.
If O(f(n))<O(h(n)) then O(f(n)+h(n))=O(h(n)).
Example:
O(n2logn+n3)=O(n3)
Multiplication Rule:O(f(n)*h(n))=O(f(n))*O(h(n))
Example:
O((n3+2n2+3nlogn+7)(8n2+5n+2))=O(n5)
Determine Complexity of Code Structures
76
Loops: for, while, and do-while:
Complexity is determined by the number of iterations in the loop times the
complexity of the body of the loop.
Examples:
for(int i=0;i<n; i++) O(n)
sum=sum-i;
for(int i=0; i<n*n; i++) O(n2)
sum=sum+i;
i=1;
while(i<n) Olog(n)
{
sum=sum+i;
i=i*2;
}
Determine Complexity of Code Structures Continue
77
Nested Loops: Complexity of inner loop* complexity of outer loop.
Examples:
sum=0
for(int i=0; i<n; i++)
for(int j=0; j<n; j++) O(n2)
sum+=i*j;
i=1;
while(i<=n){
j=1;
while(j<=n){
statements of constant complexity
j=j*2; O(nlogn)
}
i=i+1;
}
Determine Complexity of Code Structures Continue
78
Sequence of statements: Use Addition rule
O(s1; s2; s3; … sk) = O(s1) + O(s2) + O(s3) + … + O(sk)
= O(max(s1, s2, s3, . . . , sk))
Example:
for (int j = 0; j < n * n; j++)
sum = sum + j;
for (int k = 0; k < n; k++)
sum = sum -l;
System.out.print("sum is now ” + sum);
Complexity is O(n2) + O(n) +O(1) = O(n2)
Determine Complexity of Code Structures Continue
79
If Statement: Take the complexity of the most expensive case :
Determine Complexity of Code Structures Continue
80
Sometimes if-else statements must carefully be checked:
O(if-else) = Max[O(Condition), O(if), O(else)
Abstract Data Type
81
An Abstract Data Type ADT Abstract Data Type(ADT): a definition for a data
type in terms of a set of values and a set of operations on that data type.
ADT: A mathematical description of an object and the set of operations on the
object. Like Stack, queue, linked list,….
An ADT specifies:
1.Data stored.
2.Operations on the data.
3.Error conditions associated with operations.
Stack
82
A stack data structure could use an array, a linked list, or any thing that can hold
data, stores arbitrary objects, in which data is added and removed at only one end
called the top. It supports the following main operations:
push(object o): inserts element o.
pop(): removes and returns the last inserted element.
top(): returns a reference to the last inserted element without removing it.
isEmpty(): returns a Boolean value indicating whether no elements are stored.
size(): returns the number of elements stored.
isFull(): checks weather stack is full or not.
Stack Continue
83
To add(push) an item to the stack, it must be placed on the top of the stack.
To remove(pop) an item from the stack, it must be removed from the top of the
stack too.
Thus, the last element that is pushed in to the stack, is the first element to be
popped out from the stack. i.e. ,Last In First Out(LIFO)
Stack Continue
84
Stack Applications
85
Reversing a sequence of string.
Checking palindrome sequences.
Store the return address when use the CALL interrupt.
Converting expression from infix to prefix or prefix to infix and evaluation the
expression which found in any form above.
Page-visited history in a Web browser
Undo sequence in a text editor
)Lecture 6 (Stack
Lecturer
Kanar Shukr Muhamad
Data Structure
and
Algorithm Design
2019-2020
University of Salahaddin-HawlerCollege of EngineeringSoftware and Informatics Engineering DepartmentFirstYear Class
Stack
87
ئ م كات تان باش قوتابيان
يوادارم ت وذروست باش به
ژی شمم پراتيک تان بۆ دادەويمئةم واو ي ش جوان بخويىه بو رو
https://drive.google.com/open?id=1b2etpdkMRBFkvUCv4L9NIJwPQXf7JkuU
Stack
88
A stack data structure could use an array, a linked list, or any thing that can hold
data, stores arbitrary objects, in which data is added and removed at only one end
called the top. It supports the following main operations:
push(object o): inserts element o.
pop(): removes and returns the last inserted element.
top(): returns a reference to the last inserted element without removing it.
isEmpty(): returns a Boolean value indicating whether no elements are stored.
size(): returns the number of elements stored.
isFull(): checks weather stack is full or not.
Stack Continue
89
To add(push) an item to the stack, it must be placed on the top of the stack.
To remove(pop) an item from the stack, it must be removed from the top of the
stack too.
Thus, the last element that is pushed in to the stack, is the first element to be
popped out from the stack. i.e. ,Last In First Out(LIFO)
Stack Continue
90
Stack Applications
91
Reversing a sequence of string.
Checking palindrome sequences.
Store the return address when use the CALL interrupt.
Converting expression from infix to prefix or prefix to infix and evaluation the
expression which found in any form above.
Page-visited history in a Web browser
Undo sequence in a text editor
Exception
92
Attempting the execution of an operation of ADT may some times cause an error
condition, called an exception.
Exceptions are said to be “thrown” by an operation that can not be executed.
In the Stack ADT, operations pop can not be performed if the stack is empty.
Attempting the execution of pop on an empty stack throws an
EmptyStackException
Stack Implementation
93
Stack is an order collection of items, it may be declared as array or structure
containing two objects.
As array we can define the stack as follows:
int stack[max_size_of_stack];
int top;
Note that stack variable can be of any data type (integer, float, etc.) while top must
be of type integer always.
Stack Algorithms
94
A simple way of implementing the stack uses an array.
We add elements from left to right.
A variable keeps track of the index of the top element.
1.Num_Of_Elements algorithm: Used to returns number of the elements in the
stack
Num_Of_Elements():
return top + 1
Stack Algorithms Continue
95
2.Stack full algorithm: This algorithm is use to check if stack is full or not, it is
called from push algorithm.
isFull()
if top=maxsize-1 then
return true
Stack Algorithms Continue
96
3. Stack empty algorithm:
This algorithm is used to check if stack is empty or not, it is called from pop
algorithm.
isEmpty()
if top=-1 then
return true
Stack Algorithms Continue
97
4. PUSH algorithm:
The array storing the stack elements may become full, a push operation will then
throw a FullStackException
PUSH(item)
if isFull() then
begin
print or throws FullStackException
exit
end
else
begin
top ← top + 1
S[top] ← item
end
Stack Algorithms Continue
98
5. POP algorithm: To return elements from the stack
POP()
if isEmpty() then
begin
print or throw EmptyStackException
exit
end
else
begin
return S[top]
top ← top − 1
end
Stack Algorithms Continue
99
6.Clear_Stack: This algorithm is used to make the stack empty.
clear()
top=-1
Performance and Limitations
100
Performance
Let n be the number of elements in the stack.
The space used is O(n).
Each operation runs in time O(1).
Limitations
The maximum size of the stack must be defined a priori, and can not be
changed.
Trying to push a new element in to a full stack causes an implementation-
specific exception
Convert Infix to Postfix
101
1. Infix: A+B Here arithmetic operator in the middle.
2. Postfix: AB+ Here arithmetic operator at the end.
3. Prefix: +AB Here arithmetic operator at the begin.
In computer the compiler covert infix expression top postfix expression by using a
stack.
Algorithm of converting infix expression to postfix expression by using single
stack.
1. We use single stack to store the operator signal.
2. Check arithmetic expression character by character from left to right.
Convert Infix to Postfix Continue
102
3. Character may be:
1. If character is operand (a to z) then output string.
2. If character is left bracket “(“ then push in stack
3. if character is operator ( +,-,*,/) then pop all operators from stack that have
priority greater or equal than new operator to the output string then push
new operator to the stack.
4. if character is right bracket “)‟, pop all operators from stack until left
bracket to the output string , ignore left and right brackets do not add to the
output string.`
Convert Infix to Postfix Continue
103
4. If you finished the arithmetic expression then popped all operators from stack to
the output string. The final shape of output string is postfix expression.
The order of precedence:
Exponentiation ^
* ,/
+ ,-
Equivalent(=,<,<=,>,>=.!=)
NOT
AND,%
OR
Convert Infix to Postfix Continue
104
E.x/ Convert infix to postfix: (6 – 2) * (5+4)
O/P StringStackI/PStep No.
((1
6(62
6( --3
6 2( -24
6 2 -null)5
6 2 -**6
6 2 -* ((7
6 2 - 5* (58
6 2 - 5* ( ++9
6 2 – 5 4* ( +410
6 2 – 5 4 +*)11
6 2 – 5 4 + *nullnull12
Convert Infix to Postfix Continue
105
E.x/ Convert Infix to Postfix
Queue Lecture 7
Lecturer
Kanar Shukr Muhamad
Data Structure
and
Algorithm Design
2019-2020
University of Salahaddin-HawlerCollege of EngineeringSoftware and Informatics Engineering DepartmentFirstYear Class
107
ئ م كات تان باش قوتابيان
يوادارم ت وذروست باش به
م ان شاءهللا ژی شمم پراتيک تان بۆ دادەويئةم واو ي ش جوان بخويىه بو رو
https://drive.google.com/open?id=1yFOC9jfmchIbHM5qQwOa3TWO6Q3CsDWM
Queue
108
The Queue ADT stores arbitrary objects.
Queues are linear data structures in which we add elements to one end and remove
them from the other end.
The first item to be en-queued is the first to be de-queued. Queue is therefore
called a First In First Out (FIFO) structure.
Main queue operations:
No_Elements(): returns the number of elements stored.
isEmpty(): returns a Boolean indicating whether no elements are stored.
isFull(): return false or true if queue is full or not.
Queue Continue
109
Enqueue (Object o): inserts an element at the end of the queue.
Dequeue(): removes and returns the element at the front of the queue.
Clear(): reset the queue
In queue there are two index for two end of queue one for addition called rear and other
is front for deletion.
Notes:
At the beginning Front=Rear=-1, in C++.
If Front=Rear=-1 then queue is empty.
If Rear=(maxsize-1) then the queue is full.
110
QueueisFullisEmptyNo_Of_Elements
(Rear-Front)
FrontRearCase
Falsetrue-1 - (-1)= 0-1-1
AFalseFalse0 - (-1)= 1-10enqueue(A)
ABFalseFalse1 - (-1)= 2-11enqueue(B)
ABCFalseFalse2 - (-1)= 3-12enqueue(C)
BCFalseFalse2 - 0 = 202dequeue()
CFalseFalse2 - 1 = 112dequeue()
CDTrueFalse3 - 1 = 213enqueue(D)
DTrueFalse3 - 2 = 123dequeue()
DTrueFalse3 - 2 = 123enqueue(E)
TrueTrue3 - 3 = 033dequeue()
TrueTrue3 - 3 = 033enqueue(F)
TrueTrue3 - 3 = 033dequeue()
Applications of Queue
111
Waiting lines: Queues are commonly used in systems where waiting line has to be
maintained for obtaining access to a resource. For example, an operating system
may keep a queue of processes that are waiting to run on the CPU.
Access to shared resources (e.g., printer).
Multi programming.
Exceptions
112
Attempting the execution of dequeue or front on an empty queue throws an
EmptyQueueException.
Attempting the execution of enqueue on an full queue throws an
FullQueueException.
Queue Algorithms Continue
113
Note:
Max_Size: Size of the queue.
front: end of deletion.
rear: end for addition.
Q: Queue.
Queue Algorithms Continue
114
1.No. of elements in the queue algorithm: return number of the elements in the
queue
No_Element()
return rear-front
2. Queue is empty algorithm: check if the queue is empty or not
isEmpty()
return (rear=-1 or rear==front)
3. Queue is full algorithm: check if the queue is full or not:
isfull()
return rear=Max_Size-1
Queue Algorithms Continue
115
4. Enqueue algorithm: Adding an element to queue
enqueue(item)
begin
if isFull()
over flow exit
else
rear ←(rear + 1)
Q[rear] ←item
end
Queue Algorithms Continue
116
5. Dequeue Algorithm: Deleting an element from queue, throws an exception if
the queue is empty.
dequeue()
begin
if isEmpty()
empty queue exit
else
front←(front + 1)
item ←Q[front]
return item
end
Queue Algorithms Continue
117
6. Clear queue algorithm: Reinitialize or reset the queue
clear()
begin
set Front to-1
set Rear to-1
end
Circular Queue Lecture8
Lecturer
Kanar Shukr Muhamad
Data Structure
and
Algorithm Design
2019-2020
University of Salahaddin-HawlerCollege of EngineeringSoftware and Informatics Engineering DepartmentFirstYear Class
119
ئ م كات تان باش قوتابيان
يوادارم ت وذروست باش به
واوي روي ا , پراتيکم بۆتان دائةم واو ي ش جوان بخويىه
١٠/٤/٢٠٢٠گرتن كوتا كاتي وه ر
https://drive.google.com/open?id=16-wPKRma_tSYbsyR0ufOKhVZmZskKRW9
Circular Queue
120
Circular Queue is a linear data structure in which the operations are performed
based on FIFO (First In First Out) principle and the last position is connected
back to the first position to make a circle. It is also called ‘Ring Buffer’
In a normal Queue, we can insert elements until queue becomes full. But once
queue becomes full, we can not insert the next element even if there is a space
in front of queue
Circular queue avoids the wastage of space in a regular queue.
Circular Queue
121
As you can see in the above image, after a bit of enqueueing and dequeueing,
the size of the queue has been reduced.
The indexes 0 and 1 can only be used after the queue is reset.
Circular Queue solves this by the process of circular increment i.e. when we
try to increment any variable and we reach the end of queue, we start from the
beginning of queue.
122
Circular QueueisFullisEmptyFrontRearCase
Falsetrue-1-1
AFalseFalse00enqueue(A)
BAFalseFalse01enqueue(B)
CBAFalseFalse02enqueue(C)
CBFalseFalse12dequeue()
DCBFalseFalse13enqueue(D)
DCFalseFalse23dequeue()
DCEFalseFalse20enqueue(E)
DEFalseFalse30dequeue()
DFEFalseFalse31enqueue(F)
DGFEFalseFalse32enqueue(G)
DGFETrueFalse32enqueue(H)
Circular Queue Algorithms
123
1. Circular Queue is_empty algorithm: check if the circular queue is empty or not
isEmpty()
return (front == -1)
2. Circular Queue is full algorithm: check if the queue is full or not:
isfull()
if((front==0 && rear==SIZE-1) || (front==rear+1))
“Queue is full.”
Case1:
Case2:
Rear=3Front=0
DCBA
Front=2Rear=1
DCFE
Circular Queue Algorithms Continue
124
3. Enqueue algorithm: Adding an element to queue
enqueue(item)
beign
if isFull()
{over flow exit}
else
if(rear == -1)
{ rear = 0; front = 0; }//it becomes 1st element
else if(rear == SIZE-1)
rear = 0;//return back there is a space
else
rear++;//store it regularly
queue[rear] = item;
end
Circular Queue Algorithms Continue
125
4. Dequeue Algorithm: Deleting an element from queue, throws an exception if
the queue is empty.
dequeue()
begin
if isEmpty()
“empty queue” exit
else{
item = queue[front];
if(front == rear)
{front = -1;rear = -1;}// We have just one element
else if(front == SIZE-1)
front = 0;//return back
else
front++;} //delete regularly
end