data structure and algorithm design · data structure 10 a data structure is a logical...
TRANSCRIPT
![Page 1: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/1.jpg)
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
![Page 2: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/2.jpg)
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
![Page 3: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/3.jpg)
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.
![Page 4: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/4.jpg)
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
![Page 5: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/5.jpg)
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
![Page 6: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/6.jpg)
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.
![Page 7: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/7.jpg)
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
![Page 8: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/8.jpg)
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.
![Page 9: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/9.jpg)
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
![Page 10: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/10.jpg)
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.
![Page 11: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/11.jpg)
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.
![Page 12: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/12.jpg)
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
![Page 13: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/13.jpg)
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.
![Page 14: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/14.jpg)
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.
![Page 15: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/15.jpg)
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.
![Page 16: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/16.jpg)
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)
![Page 17: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/17.jpg)
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.
![Page 18: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/18.jpg)
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.
![Page 19: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/19.jpg)
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.
![Page 20: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/20.jpg)
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
![Page 21: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/21.jpg)
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.
![Page 22: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/22.jpg)
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.
![Page 23: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/23.jpg)
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
![Page 24: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/24.jpg)
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. }
![Page 25: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/25.jpg)
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.
![Page 26: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/26.jpg)
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.
![Page 27: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/27.jpg)
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.
![Page 28: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/28.jpg)
Arithmetic Operator
28
The main C++ arithmetic operator are the following:
+ for addition
- for subtraction
* for multiplication
/ for division
% for division with remainder
![Page 29: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/29.jpg)
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:??????
![Page 30: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/30.jpg)
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 %)
![Page 31: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/31.jpg)
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.
![Page 32: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/32.jpg)
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.
![Page 33: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/33.jpg)
If-Else Statements Continue
33
The table below is the full list of comparison operators in C++:
![Page 34: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/34.jpg)
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;
{
![Page 35: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/35.jpg)
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.
![Page 36: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/36.jpg)
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.
![Page 37: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/37.jpg)
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;
![Page 38: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/38.jpg)
Lecture 3
Lecturer
Kanar Shukr Muhamad
Data Structure
and
Algorithm Design
2019-2020
University of Salahaddin-HawlerCollege of EngineeringSoftware and Informatics Engineering DepartmentFirstYear Class
![Page 39: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/39.jpg)
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;
}
![Page 40: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/40.jpg)
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.
![Page 41: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/41.jpg)
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.
![Page 42: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/42.jpg)
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;
}
![Page 43: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/43.jpg)
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
![Page 44: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/44.jpg)
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.
![Page 45: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/45.jpg)
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;
![Page 46: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/46.jpg)
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.
![Page 47: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/47.jpg)
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);
![Page 48: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/48.jpg)
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
}
![Page 49: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/49.jpg)
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;
}
![Page 50: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/50.jpg)
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)
![Page 51: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/51.jpg)
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.
![Page 52: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/52.jpg)
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;
}
![Page 53: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/53.jpg)
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
![Page 54: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/54.jpg)
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.
![Page 55: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/55.jpg)
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;
}
![Page 56: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/56.jpg)
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
}
![Page 57: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/57.jpg)
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..
![Page 58: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/58.jpg)
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
![Page 59: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/59.jpg)
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.
![Page 60: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/60.jpg)
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
![Page 61: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/61.jpg)
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
![Page 62: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/62.jpg)
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;
};
![Page 63: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/63.jpg)
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;
![Page 64: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/64.jpg)
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
![Page 65: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/65.jpg)
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;
};
![Page 66: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/66.jpg)
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;
}
![Page 67: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/67.jpg)
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.
![Page 68: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/68.jpg)
Structure Mapping Function Continue
68
![Page 69: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/69.jpg)
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
![Page 70: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/70.jpg)
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
![Page 71: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/71.jpg)
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.
![Page 72: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/72.jpg)
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.
![Page 73: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/73.jpg)
Asymptotic Complexity Continue
73
Some Big-O complexity classes in order of magnitude from smallest to highest:
![Page 74: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/74.jpg)
Big-O Examples
74
![Page 75: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/75.jpg)
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)
![Page 76: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/76.jpg)
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;
}
![Page 77: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/77.jpg)
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;
}
![Page 78: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/78.jpg)
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)
![Page 79: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/79.jpg)
Determine Complexity of Code Structures Continue
79
If Statement: Take the complexity of the most expensive case :
![Page 80: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/80.jpg)
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)
![Page 81: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/81.jpg)
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.
![Page 82: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/82.jpg)
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.
![Page 83: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/83.jpg)
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)
![Page 84: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/84.jpg)
Stack Continue
84
![Page 85: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/85.jpg)
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
![Page 86: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/86.jpg)
)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
![Page 87: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/87.jpg)
Stack
87
ئ م كات تان باش قوتابيان
يوادارم ت وذروست باش به
ژی شمم پراتيک تان بۆ دادەويمئةم واو ي ش جوان بخويىه بو رو
https://drive.google.com/open?id=1b2etpdkMRBFkvUCv4L9NIJwPQXf7JkuU
![Page 88: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/88.jpg)
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.
![Page 89: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/89.jpg)
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)
![Page 90: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/90.jpg)
Stack Continue
90
![Page 91: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/91.jpg)
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
![Page 92: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/92.jpg)
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
![Page 93: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/93.jpg)
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.
![Page 94: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/94.jpg)
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
![Page 95: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/95.jpg)
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
![Page 96: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/96.jpg)
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
![Page 97: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/97.jpg)
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
![Page 98: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/98.jpg)
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
![Page 99: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/99.jpg)
Stack Algorithms Continue
99
6.Clear_Stack: This algorithm is used to make the stack empty.
clear()
top=-1
![Page 100: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/100.jpg)
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
![Page 101: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/101.jpg)
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.
![Page 102: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/102.jpg)
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.`
![Page 103: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/103.jpg)
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
![Page 104: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/104.jpg)
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
![Page 105: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/105.jpg)
Convert Infix to Postfix Continue
105
E.x/ Convert Infix to Postfix
![Page 106: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/106.jpg)
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
![Page 107: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/107.jpg)
107
ئ م كات تان باش قوتابيان
يوادارم ت وذروست باش به
م ان شاءهللا ژی شمم پراتيک تان بۆ دادەويئةم واو ي ش جوان بخويىه بو رو
https://drive.google.com/open?id=1yFOC9jfmchIbHM5qQwOa3TWO6Q3CsDWM
![Page 108: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/108.jpg)
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.
![Page 109: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/109.jpg)
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.
![Page 110: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/110.jpg)
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()
![Page 111: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/111.jpg)
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.
![Page 112: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/112.jpg)
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.
![Page 113: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/113.jpg)
Queue Algorithms Continue
113
Note:
Max_Size: Size of the queue.
front: end of deletion.
rear: end for addition.
Q: Queue.
![Page 114: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/114.jpg)
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
![Page 115: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/115.jpg)
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
![Page 116: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/116.jpg)
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
![Page 117: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/117.jpg)
Queue Algorithms Continue
117
6. Clear queue algorithm: Reinitialize or reset the queue
clear()
begin
set Front to-1
set Rear to-1
end
![Page 118: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/118.jpg)
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
![Page 119: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/119.jpg)
119
ئ م كات تان باش قوتابيان
يوادارم ت وذروست باش به
واوي روي ا , پراتيکم بۆتان دائةم واو ي ش جوان بخويىه
١٠/٤/٢٠٢٠گرتن كوتا كاتي وه ر
https://drive.google.com/open?id=16-wPKRma_tSYbsyR0ufOKhVZmZskKRW9
![Page 120: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/120.jpg)
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.
![Page 121: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/121.jpg)
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.
![Page 122: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/122.jpg)
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)
![Page 123: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/123.jpg)
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
![Page 124: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/124.jpg)
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
![Page 125: Data Structure and Algorithm Design · Data Structure 10 A data structure is a logical representation to understand physical representation. “Clever”ways to organize information](https://reader034.vdocument.in/reader034/viewer/2022051604/60044718d2735d2b665da8f1/html5/thumbnails/125.jpg)
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