Qa ssiam, Yee
U _aiversity ERR
Computer College, Department of Computer Science, Kingdom of Saudi Arabia
Data Structures (CS-214)
INSTRUCTOR:
Shahid Iqbal Lone
e_mail:
[email protected]
COURSE BOOK:
1 Tanenbaum Aaron M, Langsam Yedidyah, Augenstein J Moshe, Dara Structures
using C.
LIST OF REFERENCE MATERIAL:
1. Seymour Lipschutz, Theory and Problems of data Structures, Schaum's Series,
Tata McGraw Hill, 2004.
Tremblay J.P and Sorenson P.G, An introduction to data structures with
applications, Tata McGraw Hill, 2 Edition.
3. Gilberg, F Richard & Forouzan, A Behrouz, Data Structures A Pseudocode
approach with C, Thomson Brooks/Cole Publications,1998,
OBJECTIVES:
With a dynamic learn-by-doing focus, this document encourages students to explore data
structures by implementing them, a process through which students discover how data
structures work and how they can be applied. Providing a framework that offers
feedback and support, this text challenges students to exercise their creativity in both
programming and analysis. Each laboratory work creates an excellent hands-on learning
opportunity for students. Students will be expected to write C-language programs,
ranging from very short programs to more elaborate systems. Since one of the goals of
this course is to teach how to write large, reliable programs. We will be emphasizing the
development of clear, modular programs that are easy to read, debug, verify, analyze, and
modify.
PRE-RE
ITE:
A good knowledge of c-language, use of Function and structures.
© nitro” "professionalDATA STRUCTURES (CSC-214)
Data:
Data are simply collection of facts and figures. Data are values or set of
values. A data item refers to a single unit of values.
Data items that are divided into sub items are group items; those that are not
are called elementary items. For example, a student's name may be divided into
three sub items - [first name, middle name and last name] but the ID of a student
would normally be treated as a single item.
Student
1D Address Age Gender
rst Middle Last
Street Area
In the above example ( ID, Age, Gender, First, Middle, Last, Street, Area ) are
elementary data items, whereas (Name, Address ) are group cata items,
An entity is something that has certain attributes or properties which may be
assigned values, The values themselves may be either numeric or non-numeric.
Example:
Attributes: Name Age Gender Social Society number
Values: Hamza 20 M 134-24-5533
Ali Rizwan 23 M 234-9988775
Fatima 20 F 345-7766443
Entities with similar attributes (e.g. all the employees in an organization)
form an entity set. Each attribute of an entity set has a range of values, the set of all
possible values that could be assigned to the particular attribute.
The term “information” is sometimes used for data with given attributes, of,
in other words meaningful or processed data.
A field is a single elementary unit of information representing an attribute of
an entity, a record is the collection of field values of a given entity and a file is the
collection of records of the entities in a given entity set.
Data Structure:
In computer science, a data structure is a particular way of storing and
organizing data in a computer's memory so that it can be used efficiently. Data may
be organized in many different ways; the logical or mathematical model of a
particular organization of data is called a data structure. The choice of a particular
data model depends on the two considerations first; it must be rich enough in
structure to mirror the actual relationships of the data in the real world. On the other
hand, the structure should be simple enough that one can effectively process the
data whenever necessary.
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia
@ nitro” profe:
sionalDATA STRUCTURES (CSC-214)
Categories of Data Structure:
The data structure can be classified in to major types:
Linear Data Structure
Non-linear Data Structure
1. Linear Data Structur
A data structure is said to be linear if its elements form any sequence. There
are basically two ways of representing such linear structure in memory.
a) One way is to have the linear relationships between the elements represented
by means of sequential memory location. These linear structures are called
arrays.
b) The other way is to have the linear relationship between the elements
represented by means of pointers or links.
These linear structures are called linked lists.
The common examples of linear data structure are
* Arrays
* Queues
= Stacks
ked
2. Non-linear Data Structure:
This structure is mainly used to represent data containing a hierarchical
relationship between elements.
e.g. graphs, family trees and table of contents.
Arrays:
The simplest type of data structure is a linear (or one dimensional) array. A
list of a finite number n of similar data referenced respectively by a set of
consecutive numbers, usually 1, 2, 3. 1n. if we choose the name A for the
array, then the elements of A are denoted by subscript notation
As Az As... Ay
or by the parenthesis notation
A (1), A (2), A (3)... A(n)
or by the bracket notation
A(t], A[2],A[3]..-..-AIn]
Example:
A linear array A[8] consisting of numbers is pictured in following figure,
1 2);3)4 45 6,{7]s
A] AN) AR) AG] A] ANS) ANB] AT]
int [8] = (1.2.3. 4.5. 6 7. Ob:
Linked Li
‘A linked list, or one way list Is a linear collection of data elements, called
nodes, where the linear order is given by means of pointers. Each node is
divided into two parts:
> The first part contains the information of the element/node
> The second part contains the address of the next node (link /next
pointer field) in the list.
Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia
@ nitro” professionalDATA STRUCTURES (CSC-214)
There is a special pointer Start/List contains the address of first node in the
list, If this special pointer contains null, means that List is empty.
Example:
stat [9
Tree:
Data frequently contain a hierarchical relationship between various elements.
The data structure which reflects this relationship is called a rooted tree graph or,
simply, a tree.
Student
ID# Address Age Gender
fst Middle Last
Street Area
Graph:
Data sometimes contains a relationship between pairs of elements which is
not necessarily hierarchical in nature, e.g. an airline flights only between the cities
connected by lines. This data structure is called Graph.
Queue:
‘A queue, also called FIFO system, is a linear list in which deletions can take
place only at one end of the list, the Font of the list and insertion can take place only
at the other end Rear.
Stack:
It is an ordered group of homogeneous items of elements. Elements are added to
and removed from the top of the stack (the most recently added items are at the
top of the stack). The last element to be added is the first to be removed (LIFO
Last In, First Out).
Data Structures Operations:
The data appearing in our data structures are processed by means of certain
operations. In fact, the particular data structure that one chooses for a given
situation depends largely in the frequency with which specific operations are
performed.
The following four operations play a major role in this text:
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia
@ nitro” profe:
sionalDATA STRUCTURES (CSC-214)
% Traversing: accessing each record/node exactly once so that certain items in
the record may be processed. (This accessing and processing is sometimes
called “visiting” the record.)
+ Searching: Finding the location of the desired node with a given key value,
or finding the locations of all such nodes which satisfy one or more conditions.
+ Inserting: Adding @ new node/record to the structure,
Deleting: Removing a node/record from the structure,
Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia
nm nitro” "professionalDATA STRUCTURES (CSC-214)
ARRAYS IN C (Single Dimension)
‘Arrays ate preferred for situations which require similar type of data items to be stored together.
An array isa finite collection of similar elements stored in adjacent memory locations. By finite we
‘mean that there are specific number of elements in an array and similar implies that all the elements in
an array are of the same type. For example, an array may contain all integers or all characters.
‘Thus an aray isa collection of variables of the same type that are referred by a common name. The
‘elements of the array are referenced respectively by an index set containing n consecutive numbers. An
array with m number of elements is referenced using an index that ranges from 0 to m=1. The lowest
index of an array is called its lower bound and highest index is called the upper bound. The number of
elements in an aray is called its range. The elements of an array A{n} containing m elements are
referenced as A(0], A(1], A(2]... A(n-1] where 0 is the lower bound and ‘n-I" is the upper bound
of the array.
ot example:
fot AION = (5,051,415 45,071,215
CC Cn ae ee OR saeco
sts [eis [se [8s fw 1 [3 [ws
‘oo ie) ———ntnesses
Representation of Linear Arrays in Memory
The memory of computer is simply a sequence of addressed locations
as shown in Fig. Let A bea linear array stored in the memory of
computer as given in above figure
‘Add( A[k]) = address of the A\[k] element of the array A
As the elements of the array A. are stored in consecutive memory
cells, the computer does not need to keep track of the address of
every element of the array. It only needs to keep track of the address
of the first element of the array which is denoted by:
Base( A
It is called the base address of the A. Using this base address Base( A),
the computer calculates the address of any element of the array by using
the following formula
Add( A[k}) = Base( A) + w(k-lower bound)
where w is the size of the data type of the array A and k is the index number.
Using the figure given on top of this page we are calculation the address of A[5]
Add(A[5])= 100 + 4 (5-0)
Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia
@ nitro” pro
fessionalDATA STRUCTURES (CSC-214)
Decleration of the Arrays: Any array declaration contains: the array name, the
element type and the array size.
Examples:
int a(20], 6[3],<[7];
float f[5], e[2];
char m[4], n[20];
Initialization of an array is the process of assigning initial values. Typically
declaration and initialization are combined.
Examples:
float, b[3]=(2.0, 5.5, 3.14};
char name[4]= CE’, e};
int ¢[10]={0};
5. There are 10
‘subscripts in the syntax of 2-D array in which one specifies the number of rows and the other the
‘number of columns. In a two-dimensional array each element is itself an array.
‘The two-dimensional aray is also called a matrix. Mathematically, a matrix A is a collection of
‘elements “a,” for alli and j's such that 0'
100
= 100
= 100
2a
o)+(3-001
1
Loc (A(1][0]) = 100 + 4
too + 4
= 100+ 4
100 + 4
= 165
apc
SS Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia
@ nitro” professionalDATA STRUCTURES (CSC-214)
Stored as Column-Major-Order Rolraliaalal
Similar, forte column major order representation let ws consider he sume mati, F-—
10,13,24,3, 41,5,6,17,8,91,10,16%,
a [91 ho [re
Mere Me and Wed AG.) = Base(A) + WIM(k-1) + =D)
Low Addresses High Addresses
Base 00 ta a mo meee
Address
to}a1}a fis |s [or]24]6 fio] 3 jaz jis
SOI. Se, aI ART AAT ABT AWE ANT ABET ORT AAT aA
St
t____
Formula to calculate/find the address of Alj] [kI" element of a2-Damay of M x N
dimension is
AliI Ik] = base (A)+ W[M(k- ColLowBound )+(j - Row LowBound )1
where W = size of element
M= = number of Rows
Let us assume thatthe base address of the aay matrix is 100, Since We (as array is of integer
type whose sizes 4), therefore, according to the formula, address of 2 3) element in he ray matrix
wittte
Loc(Al2}[11) = 100 + 413 (1 =0)+¢2-091
fimo 3413 627
2 100 + 415)
= inn + 40
= 120
Loc (AL2][0}) = 100 + 413 (o-0)+(2-091
~ 100+ 410 + 2)
Sion 3 412)
= io + 8
190
Dynamic Arrays
Dynamic array allocation is actually a combination of pointers and dynamic memory allocation
Whereas static aays are declared prior to runtime and are reserved in stack memory, dynamic
arrays are created in the heap using the new and released from the heap using delete operators.
Start by declaring a pointer to whatever data type you want the auzay to hold. In this case I've
used int
int *my_array:
This C+ statement simply declares an integer pointer. Remember, a pointer is a variable that
holds a memory address. Declaring a pointer doesn't reserve any memory for the array - that will
be accomplished with new. The following C++ statement requests 10 integer-sized elements be
reserved in the heap with the first element address being assigned to the pointer m~_array
‘my_array = new int{10];
‘The new operator is requesting 10 integer elements from the heap. There is a possibility that there
‘might not be enough memory left in the heap, in which case your program would have to properly
apc
SS Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia
@ nitro” professionalDATA STRUCTURES (CSC-214)
handle such an error. Assuming everything went OK, you could then use the dynamically
declared array just like the static array.
Dynamic array allocation is nice because the size of the array can be determined at runtime and
then used with the new operator to reserve the space in the heap. To illustrate Tl uses dynamic
array allocation to set the size of its array at runtime.
// array allocation to set the size of its array at runtime.
#include
int main ()
(
int in
int * p:
cout << "How many numbers would you like to type?
cin >> iF
P= new int[i]; // it takes memory at run-time from #
if (p == NULL)
cout << “Error: memory could not be allocated";
else
(
for (n=07 ndis nt+)
cout << "Enter number: "s
ein >> pial
// to hold the base address of dynamic array
ntered: \n";
oe ete)
deletel] ps // it release the memory to send it back to Heap
)
return 07
}
* Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia =", .
@ nitro” professionalDATA STRUCTURES (CSC-214)
Operations on array
Traversing: means to visit all the elements of the array in an
operation is called traversing.
2- Insertion: means to put values into an array
3- Deletion / Remove: to delete a value from an array.
4- Sorting: Re-arrangement of values in an array in a specific order
(Ascending / Descending) is called sorting
5- Searching: The process of finding the location of a particular element
in an array is called searching. There are two popular searching
techniques/mechanisms
Linear search and binary search and will be discussed later.
a) Traversing in Linear Array:
It means processing or visiting each element in the array exactly once;
Let ‘A’ is an array stored in the computer's memory. If we want to display the
contents of 'A’, it has to be traversed i.e. by accessing and processing each element
of 'A’ exactly once.
Algorithm: (Traverse a Linear Array) Here LA is @ Linear array with lower
boundary LB and upper boundary UB. This algorithm traverses LA
applying an operation Process to each element of LA.
1, [Initialize counter.] Set K=LB.
2. Repeat Steps 3 and 4 while KSUB.
3. [Visit element.] Apply PROCESS to LA[K].
4 [Increase counter.] Set k=K+1.
[End of Step 2 loop.]
5. Exit
The alternate algorithm for traversing (using for loop) is
Algorithm: (Traverse a Linear Array) This algorithm traverse a linear array LA with
lower bound LB and upper bound UB.
1. Repeat for K=LB to UB
Apply PROCESS to LAK].
[End of loop]
2. Exit
This program will traverse each element of the array to calculate
the sum and then calculate & print the average of the following
array of integers.
(4, 3, 7, -1, 7, 2, 0, 4, 2, 13)
#include
#define size 10 // another way int const size = 10
int main()
{ int x[10]={4,3,7,-1,7,2,0,4,2,13}, i, sum=0,LB=0, UB=size;
float av;
for(i=LB,iALi+1])
{
hold =AUi];
ALIJ=Ali+11;
‘Ali+i]=hold;
+
+
y
}
Home Work
Write a program to determine the median of the array given below:
(9, 4, 5, 1, 7, 78, 22, 15, 96, 45,25)
Note that the median of an array is the middle element of a sorted array.
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia, =",
7 @ nitro” professionalDATA STRUCTURES (CSC-214)
‘Searching in Linear Array:
The process of finding a particular element of an array is called Searching”. If
the item is not present in the array, then the search is unsuccessful.
There are two types of search (Linear search and Binary Search)
Linear Search:
The linear search compares each element of the array with the search key
until the search key is found. To determine that @ value is not in the array, the
program must compare the search key to every element in the array, It is also called
“Sequential Search” because it traverses the data sequentially to locate the
element.
Algorithm: (Linear Search)
LINEAR (A, SKEY)
Here A. isa Linear Array with N elements and SKEY is a given item
of information to search. This algorithm finds the location of SKEY in
A and if successful, it returns its location otherwise it returns -1 for
unsuccessful
1. Repeat fori = 0 to N-t
2. if Ali] = SKEY) return i [Successful Search]
[End of loop |
3, return -1 [Un-Successful]
4. Exit.
(/* This program use linear search in an array to find the LOCATION of the given
Key value */
/* This program is an example of the Linear Search*/
#include
int const N=10;
int LinearSearch(int [ ], int); // Function Prototyping
int main()
{ int ALN]= {9, 4, 5, 1, 7, 78, 22, 15, 96, 45}, Skey, LOC;
cout<<" Enter the Search Key\n”;
cin>>Skey;
LOC = LinearSearch( A, Skey); // call a function
if(LOC == -1)
cout<<” The search key is not in the array\n Un-Successful Search\n”;
else
cout<<" The search key “<
int const N=10;
int BinarySearch(int [ ], int); // Function Prototyping
int main()
{ int A[N]= (3, 5, 9, 11, 15, 17, 22, 25, 37, 68}, SKEY, LO
cout<<” Enter the Search Key\n “;
cin> >SKEY);
LOC = BinarySearch(A, SKEY); // Function call
if(LOC == -1)
cout<<” The search key is not in the array\n";
else
cout<<" The search key "<
#include
#include
struct student
( int iy 4 bytes
char name[10]+ // 10 bytes
float grades (/ 4 bytes
int ager an
char phone[10]+ ‘/ 10
char email[1é]; // 16
M
// Prototyping of the functions
void display(struct student);
void main()
4
struct student
aden
sae
aden
aden
2,31, "5432186", "ai [email protected]");
27, "2345671", "[email protected]"]
Students Records Sheet\,
nannnnnnnnnnnnnnnannne \B\R"
AGE EHONE E-MAIL\n";
display(s1); // structure pass to function
display(s2); // structure pass to function
display (23);
display(=4);
display (ss);
?
void display(struct student
( cout<
#include
STU_GRADES
(char name [3017
int examl;
int exan2;
int exan3,
int final;
float sem_avey
char letter_grader
M
//inputs the data itens for a stude
//is passed by reference
struct STU_GRADES get_stu ( )
(ste U_GRADES student:
cout << "\a\n\n\n Enter the information for a sti
eture
cout <<" Mame: "y
cin.getline (student-name, 30, '\n")7
cout <<" Examl: "s
cin >> student .examl;
cout <<" Exam: "s
cin >> student .examz;
cout << "exam: "7
cin >> student .exam3;
cout << “final: "7
cin >> student. final;
return student?
)
/fdisplays a student's info
/fstructure is passed by value
void print_stu (struct STU_GRADES stu)
(
cout << "\n\n\nGrade report for: " << etu.nameccendl;
<< “\nexam 1\texam 2\texam 3\tfinal\n"
cout << stu-examl << "\t" << stuexam2 << "\t"
<< stu-exam3 << “\t" << stu.finaly
cout << "\n\n\nsenester average: " << se!
<< setprecision (2) << stu.sem_aver
cout << "\nsemeater grade: " << atu. letter grade;
age (iost:fixed)
we (int exl, int
int ex3, int final)
float aver
ave = float (exl + ex2 + ex3 + final)/4.0£+
return ave;
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia =", .
nine @ nitro” professionalDATA STRUCTURES (CSC-214)
7
char assign let (float average)
(
char let_grader
Af (average >= 90)
let_grade = 'A's
cise if (average >= 80)
let_grade - 'B'7
else if (avera
let_grade = 'c’
else if (average
let_grade - 'D'
else let_grade
return let_grade;
)
int main()
fi
struct STU_GRADES stur
char more;
do
(
stus get_stu ( )+
(/pass elements of the strucutre
stu.sem_ave = ve (stuvexanl, stu.exan2,
Stu.exam3, stu.final);
(/pass elements of the structure
stu. letter_¢ assign_let (stu-sem_ave);
(/pass the entire structure
print_stu (stu);
cout << "\n\m\n Enter another student? (y/n) "y
cin >> more;
//grab the carriage return since
(/oharacter data is input next
cin.ignore ();
} while (more
return 07
* Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia =", .
@ nitro” professionalDATA STRUCTURES (CSC-214)
Pointers
Pointers are a fundamental part of C. If you cannot use pointers properly then you have
basically lost all the power and flexibility that C allows. The secret to C is in its use of
pointers
C uses pointers a lot. WI
+ tis the only way to express some computations,
+ Itproduces compact and efficient code.
. It provides a very powerful tool.
C uses pointers explicitly with:
= Arrays,
. Structures,
. Functions.
NOTE: Pointers are perhaps the most difficult part of C to understand. C's
implementation is slightly different from other languages.
What is a Pointer?
A pointer is a variable which contains the address in memory of another variable. We can
have a pointer to any variable type
The operator & gives the “address of a variable”.
The indirection or dereference operator * gives the “contents of an object pointed f0
by a pointer”.
To declare a pointer to a variable do:
int *p:
NOTE: We must associate a pointer to a particular type: You can't assign the address of
a short int to a long int, for instance.
long int A=10; short int B long int *p=&A; // womg assignment;
Similarly: float *T = &B; // wong pointer assignment.
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia, 7" .
vane @ nitro” professionalDATA STRUCTURES (CSC-214)
Consider the effect of the following code
xed, y=2
tip:
It is worth considering what is going on at the machine level in memory to fully
understand how pointer work. Consider following Fig. Assume for the sake of this
discussion that variable x resides at memory location 100, y at 200 and ip at 1000. Note
A pointer is a variable and thus its values need to be stored somewhere. It is the nature of
the pointers value that is new.
inte L y2:
int op:
ip= oe:
x[a y[2 » [10
0 E 1000
y= Mp:
A yf » [im
100 200
a5
« {5 y| 2 ip | 100
we 100
pes
x[3 y[a of
1007 2
Now the assignments x = 1 and y= 2 obviously load these values into the variables. ip is
declared to be a pointer to an integer and is assigned to the address of x (&x). So ip gets
loaded with the value 100 which is the address of x.
Next y gets assigned to the contents of ip. In this example ip currently points to memory
location 100 -- the location of x. So y gets assigned to the values of x -- which is 1. After
that assignment of 3 to variable x.
Finally we can assign a value 3 to the contents of a pointer (*ip)..
Bpcie
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia
93 ae
@ nitro” professionalDATA STRUCTURES (CSC-214)
IMPORTANT: When a pointer is declared it does not point anywhere. You
must set it to point somewhere before you use it.
So wee
int tips
tip = 50:
will generate an error (program crash!!).
‘The correct use ist
// setting the
Here is ancther example prooram which will describes the usage
pointers and the contents of pointers.
#include
int main ()
(int 2-3, + S20, D0, M=0r
int *pl, *p2, *p3, *p4, *p5s_// five pointers are declared
// assigning address b, 8, D and M to these pointers
pl = 4a? p2= ab; p3 = & = 5D: Mi
sp} = “pl + ‘ps // same ass +b
coutc< *p3ccendl; // it prints
coutc< pic
void swap( int *, int *); // function p
int
(int
otyping
cours” a = “ec a
‘temp = "px
ond } int;
Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia =",
nine @ nitro” profes:
sionalDATA STRUCTURES (CSC-214)
Pointers and Structures
1x Program to describe the pointer to stuctures
Inde width; Area
couts<"\n Area= 5 P > area;
return
)
2+ Another program to
77-it is assumed that
describe the pointer to structures.
7/ in memory
#include
n> —
My_struct 2000 g———7
struct /* the structure type */ shahid
char 7* last name */ name
char /* first name */
int ages 7* age */ Hamza
ye
fname
struct tag my_struct /* define the structure */
void show_nane(struct tag *p)? /* function prototype */
int main() age [1?
(
uct tag *st_ptri /* a poin a structure */
y (ny_strust name, "Shabid") ;
the ~ operator lets us access a member of the structure pointed to by a pointer.i.e
ese the menber “fname” of “p” point
p-> fname will
ase the menber “age” of = “p
will pointer.
B-> a
See another example, which is a little bit complex:
etruct Node (
int value
struct Node* next;
in
eet
te the poin!
struct Node
etruct Node
uct Node
// Allocate the pointees
ew (Node); // (str
new (Node); // (str’
(Node)? // (strui
or
numbers in the pointes
next value next
eet poke
wines
29 Os
Shahid Iqbal (Lecturer) Computer College |
Qassim University Kingdom of Saudi Arabia . .
@ nitro” professionalDATA STRUCTURES (CSC-214)
Home Work
Exercise -1
Write a C program to read through a 10 elements array of integer type using pointers.
Search through this array to find the biggest and smallest value,
Exercise -2
‘Write a program that takes three variable (a, b, c). Rotates the values stored so that value
agoestob, b toc and € to a.
Note: make a function which takes pointers of these variables and using pointers it
rotates the values,
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia, """
@ nitro” pr
‘ofessionalDATA STRUCTURES (CSC-214)
‘STACKS:
It is an ordered group of homogeneous items of elements. Elements are added to
and removed from the top of the stack (the most recently added items are at the
top of the stack). The last element to be added is the first to be removed (LIFO:
Last In, First Out).
Astack of
cafeteria trays A stack of
neatly folded shirts
A stack isa list of elements in which an element may be inserted or deleted only at
‘one end, called TOP of the stack. The elements are removed in reverse order of that
in which they were inserted into the stack.
Basic operations:
‘These are two basic operations associated with stack:
+ Push() is the term used to insert/add an element into a stack.
+ Pop() is the term used to delete/remove an element from a stack,
‘Other names for stacks are piles and push-down lists.
There are two ways to represent Stack in memory. One is using array and other is
using linked list.
Array representation of stacks:
Usually the stacks are represented in the computer by a linear array. In the following
algorithms/procedures of pushing and popping an item from the stacks, we have
considered, a linear array STACK, a variable TOP which contain the location of the
top element of the stack; and a variable STACKSIZE which gives the maximum
number of elements that can be hold by the stack.
STACK
Data 1| Data 2[ Data 3
0 1 2 3 4 5 6 7 8
top [2 stacksize [9
Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia . .
vane @ nitro” professionalDATA STRUCTURES (CSC-214)
Stacks
r STACKSIZEL
[ls fe} CI
5 is] s 5
Bs Bia 4
ts 1S] 3 3
at ai 1
iO Mio 0
A Staci Selemens A filstack An empty Stack
top=4 top=stacksize-1 — top=-1
Push Operation
Push an item onto the top of the stack (insert an item)
STACKSIZE4 STACKSIZE.1
STACKSIZE2 STACKSIZE2
6
5 i | s
4 23 4
3 15 3
22/2 22 2
4141 41 1
34 0 34 0
Before PUSH After PUSH
(top=4, counts) (op-5, count=6)
Pasian —
32 Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia . .
nine @ nitro” professionalDATA STRUCTURES (CSC-214)
Pop Operation
Pop an item off the top of the stack (delete an item)
STACKSIZE-1 STACKSIZE.1
STACKSIZE2 STACKSIZE-2
6
5 5
23 (4 4
1s_|3 is_| 3
2 |2 2 | 2
a_i 4a. |!
34_|0 a4 |
Before POP After POP
(top=4, count: (top=3 count=4)
Algorithm for PUSH:
Algorithm: PUSH(STACK, TOP, STACKSIZE, ITEM)
1. [STACK already filled?]
If TOP=STACKSIZE-1, then: Print: OVERFLOW / Stack Full, and Return.
2, Set TOP:=TOP+1. [Increase TOP by 1.]
3. Set STACK[TOP]=ITEM. [Insert ITEM in new TOP position.)
4. RETURN
Algorithm for POP:
Algorithm: POP(STACK, TOP, ITEM)
This procedure deletes the top element of STACK and assigns it to the
variable ITEM
1, [STACK has an item to be removed? — Check for empty stack]
If TOP=-1, then: Print: UNDERFLOW/ Stack is empty, and Return,
2, Set ITEM=STACK|TOP]. [Assign TOP element to ITEM. ]
3. Set TOP=TOP-1. [Decrease TOP by 1.]
4. Return
~~ Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia .
@ nitro” prof
fessionalDATA STRUCTURES (CSC-214)
Here are the minimal operations we'd need for an abstract stack (and their typical
names);
Push: Places an element/value on rop of the stack.
vop: Removes value/element from rop of the stack.
roBnpty: Reports whether the stack is Empty or not.
roFull: Reports whether the stack is Full or not.
1. Run this program and examine its behavior.
// & Program that exercise the operations on Stack Implementing Array
// i.e. (Push, Pop, Traverse)
#include
#include
#include
fdefine STACKSIZE
J/ int const STACKSIZE =
Jf global variable and declaration
int Top--1;
int Stack[STACKSIZ=] +
void Push(int); // functions prototyping
int Pop(voi:
bool IsEmpty (void)
bool IsFull (void)
void Traverse (void):
int main( )
(int item, choices
while( 1)
(
cout<< "\n\n\n\n\n"s
seetas% STACK OPERATIONS *4*#*44+* \n\n"7
1- Push item \n 2- Pop Item \n"s
3- Traverse / Display Stack Items \n é- Ex:
\n\a\t Your choice ---> "
cin>> choice:
switch (choice)
{ case 1: 1f(IsFull())coutc< "\n Stack Full/overflow\n";
else
{cout<< "\n Enter a number: "s cim>item:
Push(item); }
breakr
case 2: if(Isimpty())cout<< "\n Stack is empty) \n"
else
{item=Pop()+
cout<< "\n deleted from Stack = "<- = 0);
1-Run this program and examine its behavior.
// & Program that exercise the operations on Stack
7/ Implementing POINTER (Linked Structures) (Dynamic Binding)
// Programed by SHAHID LONE
7/ This program provides you the concepts that how STACK is
// implemented using Pointer/Linked Structures
#include
#include
etruct node {
int infor
struct node ‘next?
)
struct node *T0P
NULL:
void push (int x)
( struct node *NewNoder
NewNode = new (node)? /
(struct node *) malloc (size!
Lf (NewNiode
ULL) { cout<<"\n\n Memeory Crash\n\n"+
returns }
NewNode->info - x+
NewNode->next = NULL?
ein pcg ce
Ca se
35 Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia .
nine @ nitro” prof
fessionalDATA STRUCTURES (CSC-214)
if(TOP == NULL) TOP = NewNodes
else
{ NewNode->next = TOP:
TOP=NewNode;
?
struct node* pop ()
{ struct node *
‘7-70!
TOP = TOP->nexty
return Ty
void Travexse()
-pnext) cout<info< "y
cin>>chr
switch (ch)
(case 1:
cout<<"\nPut a value: "7
cin>>item:
Push (item):
break:
if(IeEmpty()) (cout<<"\n\n Stack is Empty\n"s
breaks
}
T= Pop()s
cout<< T->info <<"\n\n has been deleted \n"
breaks
- 4£(rsEmpey()) {coutcc™\n\n stack is Empty\n";
break
>
Traverse ()+
break:
- exit(0)
// end of switch bl
// end of loop
zeturn 07
) // end of main function
aes
36 Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia =", .
nine @ nitro” professionalDATA STRUCTURES (CSC-214)
‘Application of the Stack (Arithmetic Expressions)
INFIX, POSTFIX AND PREFIX
NOTATIONS
Tans T Posts Prone
AB. AB+ AB
A=B.C ABTC. =ABC
HBC) AB+CD-* =AB-CD,
Infix, Postfix and Prefix notations are used in many
calculators. The easiest way to implement the
Postfix and Prefix operations is to use stack. Infix
and prefix notations can be converted to postfix
notation using stack
The reason why postfix notation is preferred is that
you don't need any parenthesis and there is no
prescience problem.
Stacks are used by compilers to help in the process of converting infix to postfix
arithmetic expressions and also evaluating arithmetic expressions. Arithmetic
expressions consisting variables, constants, arithmetic operators and parentheses.
Humans generally write expressions in which the operator is written between the
operands (3 + 4, for example). This is called infix notation. Computers “prefer”
postfix notation in which the operator is written to the right of two operands. The
preceding infix expression would appear in postfix notation as 3.4 +
To evaluate @ complex infix expression, a compiler would first convert the expression
to postfix notation, and then evaluate the postfix version of the expression. We use
the following three levels of precedence for the five binary operations.
Precedence Binary Operations
Highest Exponentiations (“)
Next Highest Multiplication (*), Division (7) and Mod (%)
Lowest Addition (+) and Subtraction (-)
For example:
(66 + 2) * 5 - 567/42
to postfix
66 22 +5* 567 42/ -
Transforming Infix Expression into Postfix Expression:
The following algorithm transform the infix expression Q into its equivalent
postfix expression P, It uses @ stack to temporary hold the operators and left
parenthesis,
The postfix expression will be constructed from left to right using operands from Q
and operators popped from STACK.
Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia . .
vane @ nitro” professionalDATA STRUCTURES (CSC-214)
Algorithm: Infix_to_PostFix(Q, P)
‘Suppose Q is an arithmetic expression written in infix notation, This
algorithm finds the equivalent postfix expression P.
1, Push "(" onto STACK, and add ")” to the end of @
2. Scan Q from left to right and repeat Steps 3 to 6 for each element of Q until
the STACK is empty:
3. If an operand is encountered, add it to P.
4 If a left parenthesis is encountered, push it onto STACK.
5. If an operator © is encountered, then
a) Repeatedly pop from STACK and add to P each operator
(onthe top of STACK) which has the same or
higher precedence/priority than ©
b) Add © to STACK.
(End of If structure.]
6. If a right parenthesis is encountered, then:
1a) Repeatedly pop from STACK and add to P each operator (on the
top of STACK) until a left parenthesis is encountered,
b) Remove the left parenthesis. [Do not add the left parenthesis to P.]
[End of If structure.]
[End of Step 2 loop.]
7. Exit,
Convert Q: A+(B* C-(D/ ESF) *G)*H into postfix frm showing stack status
Now add“) at the end of expression A+(B*C-(D/E*F)*G)*H)
and also Push a “(" on Stack.
‘Symbol Scanned Stack Expression
¢
A ( A
+ (+ A
¢ (+ A
B (+( AB
« GC AB
c GHC ABC
- Ge ABC
( GCC ABC
D GCC ABCD
1 Gey ABC*D
E Gey ABC*DE
a (CUA ABC*DE
F C+(-% ABC*DEF
) (+(- ABC*DEF*/
* Ge ABC*DEF*/
s C* ABC*DEF*/G
) G ABC*DEF/G*-
» Ge ABC*DEF/G*-
H Ge ABC*DEF*/G*-H
) empty ABC*DEF*/G*-H*+
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia, =",
7 @ nitro” professionalDATA STRUCTURES (CSC-214)
Evaluation of Postfix Expression:
If P is an arithmetic expression written in postfix notation. This algorithm
uses STACK to hold operands, and evaluate P.
Algorithm: This algorithm finds the VALUE of P written in postfix notation.
1. Add a Dollar Sign "$” at the end of P. [This acts as sentinel.]
2. Scan P from left to right and repeat Steps 3 and 4 for each element of P
until the sentinel "$” is encountered,
3. If an operand Is encountered, put it on STACK,
4, If an operator © is encountered, then:
a) Remove the two top elements of STACK, where A is the top
element and B is the next-to—top-element.
b) Evaluate BO A.
¢) Place the result of (b) back on STACK,
[End of If structure. ]
[End of Step 2 loop.]
5. Set VALUE equal to the top element on STACK
6. Exit,
Following is an infix arithmetic expression
(5+2)*3-9/3
And its postfix is:
5 2+ 3* 9 3 / -
Now add “$” at the end of expression as a sentinel,
5 2+ 3*8 4/ -$
Scanned Elements Stack Action to do——_____
2 5, 2 Pushed on Stack
+ 7 Remove the two top elements and calculate
5 +2 and push the result on stack
3 7, 3 Pushed on Stack
= aa Remove the two top elements and calculate
7 * 3 and push the result on stack
8 21, 8 Pushed on Stack
4 21, 8, 4 — Pushed on Stack
/ 21, 2 Remove the two top elements and calculate
8 / 2 and push the result on stack
: 19 Remove the two top elements and calculate
21 - 2 and push the result on stack
$ 19 Sentinel $ encouter , Result Is on top of the STACK
Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia .
7 @ nitro” prof
fessionalDATA STRUCTURES (CSC-214)
Following code will transform an infix arithmetic expression into Postfix arithmetic
expression. You will also see the Program which evaluates a Postfix expression
// This program provides you the concepts that how an infix
// arithmetic expression will be converted into post-fix expression
// using STACK
// Conve
Y/ NOTE
sion Infix Expresst: ost-fiz
“is used for raise-to-the-power
#includeciostream.h>
#include
#include
int main()
{ int const nuli=-t;
char Q[100],?[100], #1
tack[100];// Q is infix and P is postfix array
int 7/ used to count item inserted in P
//used ag an index for P
int top=nulls // it assign -1 top
int k,i7
cout<<"Put an arithematic INFIX Expression\n\n\t\t";
Gin.getline(Q,98)) // reads an satin expression into Q as string
// it calculates the length of Q and store it in k
// following two lines will do initial work with Q and st:
21Q,")")+ // This function add} at the andar Q
stackl++top]="('; // This statement will push first ( “on
while(top!= null)
(
fox (i-O;icrkeit+)
‘
(tal)
case "3"
for (44)
{if (stack[t
stack [t
else
( Plots:
Bpcie
~~ Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia nitro™,
nitro")
sing
9 ee
rofessionalDATA STRUCTURES (CSC-214)
T
stack ++top]=gfil:
breaks
for (+s
{
if (stackit
stack(t
etack[t
else
{ Plott]
tack[top--I: ntts +
)
stack [++top]=9[417
break:
if (stack [top]
else { Flott
)
breaks
default // it means that read item is an oprand
[ot4]=Q1i]7
} /fEND OF SWITCH
//END OF FOR LOOP
} //END OF WHILE LOOP
P[n]="\0"; // this statement will put string terminator at the
// end of P which is Postfix e: don
cout<<"\n\nPOSTFIX EXPRESION 1S \n\n\t\t"<
#include
#includecmath.h>
#include
#include
>
struct node *TOP - NULL;
void push (int x)
‘ “0:
// in o+t Q = new no
(struct node +) malloc(sizeof (node) ): // creation
Q->info = x:
new node
{ cout<<"\nStack is empty\n\n"s
exit (0):
int main(void)
(chaz tr
struct node *Q, *A, *B:
cout<<"\n\n Put a post-fix arithmatic expression end with $: \n "7
while (1)
( tagetche()? // this will re
if(isdigit(t)) push(t-'0'): //
else i: *)eontinue;
else if(t=="$") break
er and store it in t
vert char into int
ie will
Bpcie
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia
sing
ea
@ nitro” professionalDATA STRUCTURES (CSC-214)
else
pop(}?
pop()?
ewiteh (t)
default: cout<<"5:
)
aie
(
push (B->info + A->info);
breaks
push(B->inZo - A->info):
breaks
push(B->ingo * A->info):
break;
"/*2 push(B->info / A->info);
breaks
‘ot: push (pow(B->info, A->info)) +
breaks
x unknown operator’
} // end of switch
// end of if structure
end of while loop
is result
info<
#include
define MAXSIZE 10 // int const MAXSIZE = 10;
// Global declarations and available to every
int Queue [MAKSIZE] +
int front = -1;
int rear = -1
int count
bool Isfmpty(){if(count==0) return true; else return falsey }
bool IsFull() { if( count
MAXSIZE) return trues else return false?)
void Enqueue (int ITEM)
fl if(IsFull()) { coute< "\n QUEUE is full\n"; returns)
if(count == 0) rear = front= 0; // firet item to enqueue
else
if(rear -- MAMSIZE -1) rear-0 ; // Circular, rear set to zero
else reartt;
Queue [rear]=I7EM+
count++
}
int Dequeue()
(
if (IsEmpty()) { cout<<"\n\nQUEUE is
int ITEM= Queue/front]:
count-.
if (count
else if (front
else front++:
0) front = rear =
MAXSIZE -1) £1
eturn ITEM;
void Traverse()
(int i;
if (IsEmpty ()) cout<<"\n\nQUEUE is empty\n"y
else
(4 = fronts
While (1)
{ cout<< Queue [i] <<"\t"s
if (4 == rear) breakr
else if(i == MAKSIZE -1) i = 0;
else itt:
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia
@ nitro” professionalDATA STRUCTURES (CSC-214)
int waing)
"soe chotee, trams
while (1)
(
cout<<"\n\n\n\n QUEUE operation\n\n";
coutc<"1-ingert value \n 2-deleted value\n";
cout<>choice:
case 1:
cout"\n put a value:"
cin>> ITEM
Enqueue (ITEM) ;bre:
case 2:
ITEM=Dequeue () +
if (ITEM!=-1) cout<
#include
(i
QUEUE *pNext;
QUEUE
QUEUE *rear-NULL, *front-NULL:
void Enqueue (int);
int Dequeue (void) +
void Traverse (void):
void main (void)
( int ITEM, choic
while( 1’)
‘
cout<<) ‘ese44+ QUEUE UNSING POINTERS +###+4+#* \n"y
cout<<" \n\n\t (1) Engueue \n\t (2) Dequeue \n"?
cout<<"\t (3) Print queue \n\t ( 4) Exit.”
cout<<" \n\n\n\t Your choice
ein>>ehoics) 7
50. “Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia
@ nitro” professionalDATA STRUCTURES (CSC-214)
Switch (choice)
“case 1: coutce *\n enter a numbers";
cin>>TTEMs
Enqueue (ITEM) +
preal
ITEM = Dequeus() 7
if (ITEM) cout<<” \n Deleted from Q = “<
- val = ITEM;
NewNode->pNext = NULL:
if (rear -- NULL)
front = vear= NewNode;
else
c
NewNodes rear
rear-ppNext =
:
)
int Dequeue (void)
(if (front == NULL) {cout<<” \n QUEUE is empty\n";
return 07
)
int ITEM = front->valy
if (font == rear ) frontqrearNULL;
glee front = front-> pNext;
rn (ITEM) 2
}
void Traverse (void)
( 4£(£ront == NULL) {cout<<
veturn: )
\n
QUEVE £ = fronts
while(f!=rear)
( cout front->val << ",
-->phei
RX cece
"Shahid Iqbal (Lecturer) Computer College
asi Unveriy Kngdom of Saud Arabia” DF
nitro”® prof
fessionalDATA STRUCTURES (CSC-214)
Linked Li
A linked list or one way list is a linear collection of data elements, called
nodes, where the linear order is given by means of “pointers”. Each node is
divided into two parts.
‘+ The first part contains the information of the element.
+ The second part called the link field contains the address of the next node in
the list.
To see this more clearly lets look at an example
Eh Ph
Te Point to next Node Null Pointer
ee
Head
Te Point to
—> Infe L493 tara ‘NULL
e748 Te End of List
‘The Head is a special pointer variable which contains the address of the first
node of the list. If there is no node available in the list then Head contains NULL
value that means, List Is empty. The left part of the each node represents the
information part of the node, which may contain an entire record of data (e.g. ID,
name, marks, age etc), the right part represents pointer/link to the next node, The
next pointer of the last node is null pointer signal the end of the list.
Advantages:
List of data can be stored in arrays but linked structures (pointers) provide
several advantages.
A linked list is appropriate when the number of data elements to be represented in
data structure is unpredictable. It also appropriate when there are frequently
insertions & deletions occurred in the list, Linked lists are dynamic, so the length of
a list can increase or decrease as necessary.
Operations on Linked List:
There are several operations associated with linked list i.e
a) Traversing a Linked List
Suppose we want to traverse LIST in order to process each node exactly once.
The traversing algorithm uses a pointer variable PTR which points to the node that is
currently being processed, Accordingly, PTR->NEXT points to the next node to be
processed 50,
Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia
@ nitro” professionalDATA STRUCTURES (CSC-214)
PTR=HEAD [ Moves the pointer to the first node of the list]
PTR=PTR->NEXT —_[ Moves the pointer to the next node in the list.]
Algorithm: (Traversing a Linked List) Let LIST be a linked list in memory. This,
algorithm traverses LIST, applying an operation PROCESS to each
element of list. The variable PTR point to the node currently being
processed.
1, Set PTR=HEAD. [Initializes pointer PTR.]
2. Repeat Steps 3 and 4 while PTRI=NULL.
3. Apply PROCESS to PTR-> INFO.
4. Set PTR= PTR-> NEXT [PTR now points to the next node.]
[End of Step 2 loop.]
5. Exit.
b) Searching a Linked List:
Let list be a linked list in the memory and a specific ITEM of information is given
to search. If ITEM is actually a key value and we are searching through a LIST for
the record containing ITEM, then ITEM can appear only once in the LIST.
Search for wanted ITEM in List can be performed by traversing the list using a
pointer variable PTR and comparing ITEM with the contents PTR->INFO of each
node, one by one of list.
Algorithm: SEARCH(INFO, NEXT, HEAD, ITEM, PREV, CURR, SCAN)
UST is a linked list in the memory. This algorithm finds the location
LOC of the node where ITEM first appear in LIST, otherwise sets
2. Repeat Step 3 and 4 while PTR+NULL:
3. if ITEM = PTR->INFO then:
Set LOC=PTR, and return, [Search is successful. ]
[End of If structure.]
4, Set PTR=PTR->NEXT
[End of Step 2 loop.]
5. Set LOC=NULL, and return. [Search is unsuccessful.]
6. Exit.
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia, =",
7 @ nitro” professionalDATA STRUCTURES (CSC-214)
Search Linked List for insertion and deletion of Node:
Both insertion and deletion operations need searching the linked list.
*To add a new node, we must identify the logical predecessor (address of
Previous node) where the new node is to be inserting.
+ To delete a node, we must identify the location (addresses) of the node to be
deleted and its logical predecessor (previous node).
Basic Search Concept
‘Assume there is a sorted linked list and we wish that after each insertion/deletion
this list should always be sorted. Given a target value, the search attempts to locate
the requested node in the linked list.
Since nodes in a linked list have no names, we use two pointers, pre (for previous)
and cur (for current) nodes. At the beginning of the search, the pre pointer is null
and the cur pointer points to the first node (Head). The search algorithm moves the
two pointers together towards the end of the list. Following Figure shows the
movement of these two pointers through the list in an extreme case scenario: when
the target value is larger than any value in the list,
a is es as eon |
D4
pre
oe er a ee
Atthe stat.
After one move
head [§- -he 9+ >: Bos Bo 2
After four moves -
Moving of pre and cur pointers in searching a linked list
Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia
@ nitro” professionalDATA STRUCTURES (CSC-214)
Values of pre and cur pointers in different cases
Case |
21
Case2 [Sf ioe
201 Hi
pre
Case3 Js
Cse4 ole Boe Bs BD >
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia, =", -
@ nitro” professionalDATA STRUCTURES (CSC-214)
Insertion into a Linked Li
If a node N is to be inserted into the list between nodes A and B in a linked list
named LIST.
Its schematic diagram would be;
Head
Inserting at the Beginning of a List:
If the linked list is sorted list and new node has the least low value already
stored in the list i.e. (if New->info < Head->info) then new node is inserted at
the beginning / Top of the list.
I (NewNode > Info info) NewNode > next= Head Head=NewNode
Wevwode Newiiode Newttode
—-E z
EL oe [102 Joes
oad Hoa
102 (2 ROL RO
“= Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia .
@ nitro” professionalDATA STRUCTURES (CSC-214)
Inserting a new node
The following algorithm inserts an ITEM into LIST.
Algorithm: INSERT( ITEM)
[This algorithm add newnodes at any position (Top, in Middle and at
End) in the List ]
1. Create a NewNode node in memory
2. Set NewNode -> INFO =ITEM. [Copies new data into INFO of new node.]
3. Set NewNode -> NEXT = NULL. [Copies NULL in NEXT of new node.)
4, If HEAD=NULL, then HEAD=NewNode and return. [Add first node in list]
5. if NewNode-> INFO < HEAD->INFO.
then Set NewNode->NEXT=HEAD and HEAD=NewNode and return
[Add node on top of existing list]
6. PrevNode = NULL, CurrNode=NULL;
7. for(CurrNode =HEAD; CurrNode != NULL; CurrNode = CurrNode ->NEXT)
{ if(NewNode->INFO <= CurrNode ->INFO)
{
break the loop
+
PrevNode = CurrNode;
} Lend of loop ]
[Insert after PREV node (in middle or at end) of the list]
8. Set NewNode->NEXT = PrevNode->NEXT and
9. Set PrevNode->NEXT= NewNode.
10.Exit.
Delete_a node from lis
The following algorithm deletes @ node from any position in the LIST.
Algorithm: DELETE(ITEM)
LIST is a linked list in the memory. This algorithm deletes the node
where ITEM first appear in LIST, otherwise it writes "NOT FOUND”
1. if Head =NULL then write: “Empty List” and return [Check for Empty List]
2. if ITEM = Head -> info then: [ Top node is to delete ]
Set Head = Head -> next and return
3. Set PrevNode = NULL, CurrNode=NULL,
4, for(CurrNode =HEAD; CurrNode != NULL; CurrNode = CurrNode ->NEXT)
{if (ITEM = CurrNode ->INFO ) then:
{
break the loop
Set PrevNode = CurrNode;
} Lend of loop ]
5. if(CurrNode = NULL) then write : Item not found in the list and return
6. [delete the current node from the list]
Set PrevNode ->NEXT = CurrNode->NEXT
Exit.
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia, =",
7 @ nitro” professionalDATA STRUCTURES
// A Program that exercise the operations
// Programed by SHAHID LONE
#include
#include
#include
atruct node
(
int infor
gtruct node texts
»
struct node *Head+NULL:
struct node *Prev, *Currs
void AddNede (int ITEM)
‘
NewNode
11 Newio
NewNlode->int i?
if (Head==NULL) { Hea
if (NewNode->info < Head->info)
(Newiode-next - Head; Head
node *NewNoder
new node?
=(struct node*)mall
for (curr
(
if( Newiode->info <
else Prev = curr;
Curr != NULL ; Curr
Curr ->info)
Newilode-next = Prev-pnext;
(CSC-214)
on Liked List
ot node) )
+ returns)
curr ->next)
break:
Prev-onext ~ NewNoder
} // end of AddNode function
void Deletetods()
( int inf:
if (Head==NULL){ cout<< "\n\n empty linked list\n"; returns}
cout<< "\n Put the info to delete: "+
cin>>int;
if(inf == Head-yinfo) // First / top node to delete
( Head - Head-onext; returns)
Prev = Curr = NULL;
for (Curr = Head ; Curr != NULL ; Curr = Curr ->next )
(
if(Curr ->info == ing)
Brev = Curr
?
i€( Curr == NULL)
cout<>chr
switch (ch)
(case 1: coutce "\n Put info/value to add: "7
cin>>int)
AddNode (inf) +
breaks
case 2: DeleteNode(); breaks
case 3: cout<< "\n Linked List Valu:
Traverse (); breaks
case 4: exit,
} // end of switch
} /f end of while leap
return 0+
} // end of main ( ) function
\n";
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia =",
nine @ nitro” profes:
sionalDATA STRUCTURES (CSC-214)
// Program designed by SHAETD TQRAL LONE Qassim University K.5.0
// This progeam describes the basics about Read/Write structures into
// a file. The file which is going to be used is a binary file.
// The logic is already discussed in the Class. Students should try to
// run this program and discuss with me if they have sone queries
#includeclostream.h>
#includecfstream.h>
#include U7 for exit keywo:
#include
#include
Jf seeseeseee GLOBAL
struct student
( int iar
char name[20];
int mi;
int m2;
int m:
OCTURE TEMPLATE *t#ts4seeeseeeses/
M
j/seeeseeesseeses GLOBAL VARIABLES ‘ettessseraeees/
// size available in the array
// used as index for insertion of new records in array
student Data[MAK]? // Array to hold all the records
int page_nor /// used for page numbers with headings in Report
Jitiocoeeitttiate FUNCTIONS PROTOTYPES +++ttetaesaaaaseaceey
void LoadList ();
void Addstudent (void) +
void SaveList (void);
void DisplayList (void) +
void Heading (void) +
[SARA ERR EER RA ERNE AHEEEAOSMRIN FUNCTIONS AP at ane Ra aH RER ERRATA ER ER/
void main (void)
(
short int choice=0;
LoadList ()+
while( 1)
(system ("els"); // this statens: are the ecreen
coute<” Main Menu"<>Choices
nto File"
ewitch( Choice )
Cheah ea
60 : Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia
@ nitro” professionalDATA STRUCTURES (CSC-214)
Radstadent( }7
breaks
case 2: page_n
DisplayList( )+
proaks
SaveList ( )+
breaks
cage 4:
SaveList( )+
cout<<"\n\n\n GoodBye!!!\n"7
exit (0):
default:
cout<<"\nInvalid Choice..
)
) // end of main() function
Jeteveseneseeaeeees FUNCTION DEFINITIONS #t#e#eeeseeeseeeseee/
void Addstudent (void)
( cout<< "\n\n [ Overflow !! 1"
cout<< "\n [ can not store new record ]\n\n\\n"s
return:
)
att?
cout<<"\n\n\n\n\n\t\t DATA FOR "<> Datain].id?
cout<< " PUT NAME: "; cin.ignore()# // cle:
cin.getline (Data in) .name, 20);
cout<< " put marke Of three subjects separated by epace: "7
cin>>Data[n] -m1>>nata([n] -m2>>pata[n] m3;
input buffer
} // End of function
void SaveList (void)
( efstrean pFiler
pFile.open ("atudent.dat", loa: tbinary);
if (pFile==NULL)
4
"Cannot Open File \n Data not saved into file\n\n";
exit (0)s
)
for (int j=0) }~ 30.0) geade-'A';
else if (per>= 70-0) graden'a';
else if (per>~ 60.0) grades *C
else if(per= 50.0) grade= "D's
glee gzade—'F';
// print record
coutccsetw (5) info. e.g. Write: pRoot -> info
[ recursive call by passing address of left child to update pRoot]
PREORDER (pRoot -> Left)
[recursive call by passing address of right child to update pRoot]
PREORDER( pRoot -> Right)
[End of If structure. ]
2. Exit.
Inorder Traversal:
Algorithm: INORDER (pRoot)
First time this function is called by passing original root into pRoot.
Here pRoot is pointers pointing to current root. This algorithm does a
Inorder traversal of T, applying by reurrsively calling same function
and updating proot to traverse in a way i.e. (LNR) Left, Node, Right.
1. If (pRoot NOT = NULL) then: —_[ does child exist ?]
L recursive call by passing address of left child to update pRoot]
PREORDER (pRoot -> Left)
ii- Apply PROCESS to pRoot-> info, e.g. Write: pRoot -> info
[ recursive call by passing address of right child to update pRoot]
ili- PREORDER( pRoot -> Right)
[End of If structure.]
2. Exit.
Postorder Traversal:
Algorithm: POSTORDER (pRoot)
First time this function is called by passing original root into pRoot.
Here pRoot is pointers pointing to current root. This algorithm does a
Postorder traversal of T, applying by rcurrsively calling same function
and updating proof to traverse in a way i.e. (LRN) Left, Right, Node.
4. IF (pRoot NOT = NULL) then: [does child exist 2]
[ recursive call by passing address of left child to update pRoot]
i- PREORDER (pRoot -> Left)
[recursive call by passing address of right child to update pRoot]
PREORDER( pRoot -> Right)
Apply PROCESS to pRoot-> info. e.g. Write: pRoot -> info
(End of If structure.]
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia, =",
7 @ nitro” professionalDATA STRUCTURES (CSC-214)
Preparing a Tree from an infix arithmetic expression
< Find operator which has low priority with respect
to execution, startng from right to left. Put it on
toot and then continue this processor on
sub-rees. The infix expression on the left side is
converted into tree, Examin this tree is a 2-Tree,
]where each node either has two nodes or zero
nodes.
*
A / \ Allinternal nodes are Operators
~ H
eee *
J \ and all leaf nodes are Oprands
A |S AHBCG DEF
G
B c |
Post Order Traversing (LRN)
JN “ABC'DEF*/G*-H* +
DOO It produce postfix expression
/\
E F Pre-Order Traversing (NLR)
+A*-*BC*/D*EFGH
it produce prefix arithmatic expression
Ae(B*C-(DIE*F)*G)°H
Recursion:
For implementing tree traversal logics as stated, two approaches are used, i.e. use
stacks or recursive functions. In this lecture notes, we will see only recursion
‘approach to implement these algorithms. Students will also use stacks to implement
these algorithms as homework.
Recursion is an important concept in computer science. Many algorithms can be best
described in terms of recursion
To make a function recursive one must consider the following
properties:
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia
@ nitro” professionalDATA STRUCTURES (CSC-214)
Following examples helps to clarify of these ideas:
/* The following program demonstrates function call of itself. The following function does
property ie. (re a
#include
void aisp( ); // prototyping
int main( }
¢
printe (*\nie110") ;
disp(); /* A fun
,
void disp( )
( peinte (welle\2");
disp( ); /* a function call to itself without any criteria */
int main(}
| int in20;
numbers (n)
,
void numbers (int a }
{ peinte(meli0\tr)s
if(a >= 1) numbers (nt1); // this needs explanation
// after each iteration, control is going far from base criteria
Factorial Function:
The product of the positive integers from m to 4, inclusive, is called "n_factorial” and
is usually denoted by nt.
It is also convenient to define 0! = 1, so that the function is defined for all
nonnegative integers. Thus we have:
oat 1
1 Q->2*1=2 Bl-> 3*2*1=6
41 -> 4°3*2"1 = 24 S!-> 5*4*3*2*1 = 120 6! -> 6*5*4*3*+2*
= 720
“= Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia, =", .
@ nitro” professionalDATA STRUCTURES (CSC-214)
Program to find the factorial of the given To find the factorial of a given number using
umber using Tor loop: recursion
ide
orial (int) ;
sam, ract)s
int main()
T
ink a, fat
printi(\oEnter any number: *);
fo, a), Aoeie oo
terials): ———t_
pring aFactonial is = %d, fa
rum 0,
)
20
Js ~~
int factorial Gta it factor nt)
ie (ae
‘fe =O fn== 1) rum ty | [iff —0 in==1) coum 1
uy r
fon* fetorile, f=" fatal);
reuun f rely f
b b 1-24
v 9
ine factorial int) int Factorial tm)
ine [ae
if ) rum 0 In= 1) ent
1
2
£28 fxgorialo-t; f=n* fetorial(o-1)
ment pe retum £
b
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia, 7" .
vane @ nitro” professionalDATA STRUCTURES (CSC-214)
Binary Search Tree:
Suppose T is a binary tree, the T is called a binary search tree or binary
sorted tree if each node N of T has the following property:
The values of at N (node) is greater than every value in the left sub tree of
N and is less than every value in the right sub tree of N.
Binary Search Tree using these values: (50, 30, 55, 25, 10, 35, 31, 20, 53, 60, 62)
Following figure shows a binary search tree. Notice that this tree is obtained by inserting
the values 13, 3, 4, 12, 14, 10, 5, 1, 8, 2, 7, 9, 11, 6, 18 in that order, starting from an
empty tee.
Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia, 7" .
vane @ nitro” professionalDATA STRUCTURES (CSC-214)
Sorting: Note that inorder traversal of a binary search tree always gives a sorted
sequence of the values. This is a direct consequence of the BST property. This
provides a way of sorting a given sequence of keys: first, create a BST with these
keys and then do an inorder traversal of the BST so created.
Inorder Travers (LNR) . 4, 5,6, 7, 8,9, 10, 11, 12, 13, 15, 18
© Search: is straightforward in a BST. Start with the root and keep moving left or
right using the BST property. If the key we are seeking is present, this search
procedure will lead us to the key. If the key is not present, we end up in a null
fink.
* Insertion in a BST is also a straightforward operation. If we need to insert an
clement n, we traverse tree starting from root by considering the above stated
rules. Our traverse procedure ends in a null link. It is at this position of this null
link that n will be included
* Deletion in BST: Let x be a value to be deleted from the BST and let N denote
the node containing the value x. Deletion of an element in a BST again uses the
BST property in a critical way. When we delete the node N containing x, it would
create a "gap" that should be filled by a suitable existing node of the BST. There
are two possible candidate nodes that can fill this gap, in a way that the BST
property is not violated: (1). Node containing highest valued element among all
descendants of left child of N. (2). Node containing the lowest valued element
among all the descendants of the right child of N. There are three possible cases
to consider:
Deleting a leaf (node with no children): Deleting a leaf is easy, as we can
simply remove it from the tree.
Deleting a node with one chil
Delete it and replace it with its child.
Deleting a node with two children: Call the node to be deleted "N". Do not
delete N. Instead, choose its in-order successor node "S". Replace the value of
with the value of “S”, (Note: § itself has up to one child.)
As with all binary trees, a node's in-order successor is the left-most child of its
right subtree. This node will have zero or one child. Delete it according to one of
the two simpler cases above.
Figure on next page illustrates several scenarios for deletion in BST.
~~ Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia, 7" .
vane @ nitro” professionalDATA STRUCTURES (CSC-214)
St “e So oe
/* delete leaf */
QD @&
e.
/* delete a node with no left (36)
pues 1
a
Qo delete 27
peckic Ze
GW) /* delete node with no on
right subtree */
D 2)
delete 13
a
/* delete node with both
left and right subtrees */
Tee cases:
1] the node is a teat Sy
Delete itimmediately
2] the node has one ehitd
‘Adst a pointer from the parent to
bypass that node
1B] the node has 2 children
‘eplace the value of that node with the
‘minimum element atthe right ubtree.
delete the minimum element Has eter
rio ehild or one child.
‘Somwoke ease 1.012
a
oe
Find lowest valued element
among the descendants of
right child
OR Find the in-order
Successor and replace it with,
node to be deleted
Deleon of ne (2) with wo chile, foe and ater
Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia,
vane a nitro” "professionalDATA STRUCTURES (CSC-214)
/* This program is about to implement different operations on Binary
Search Tree. Programmed by SHAHID LONE */
#include
#include
include
struct NODE
{
int info;
struct NODE *Left;
struct NODE *Right;
t
struct NODE *Root = NULL; // initially Root is NULL
void AttachNode( struct NODE *pRoot, struct NODE “pNew )
{
if{ Root == NULL ) // to attach first node with tree
{
+
else
{
Root = pNew; // attaches node on first root,
if (pNew->info < pRoot->info )
{ _ // traverse to left sub-tree and find null at left
if{ pRoot->Left != NULL)
AttachNode( pRoot->Left, pNew ); // recursive call
else
PRoot->Left = pNew; // attaches node on left
else
{jj traverse to right sub-tree and find null at right
if( pRoot->Right != NULL)
AttachNode( pRoot->Right, pNew ); // recursive call
else
pRoot->Right = pNew; // attaches node on left
t
void Insert(int x)
{
struct NODE *NewNod.
NewNode->Left
NewNode->Righ
NewNode->info
AttachNode( Root, NewNode );
(struct NODE *) malloc(sizeof(NODE));
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia, =",
7 @ nitro” professionalDATA STRUCTURES (CSC-214)
void Pre_Order(struct NODE *pRoot)
if (pRoot)
‘ printf("9od\t",pRoot->info);
Pre_Order(pRoot-> Left);
Pre_Order(pRoot-> Right);
void Post_Order(struct NODE *pRoot)
if (pRoot)
Post_Order(pRoot->Left);
Post_Order{pRoot->Right);
printf("%d\t",pRoot->info);
void In_Order(struct NODE *pRoot)
if( pRoot )
‘ if(pRoot->Left) In_Order(pRoot->Left);
printf("%d\t",pRoot->info);
if(pRoot->Right) In_Order(pRoot->Right);
void DisplayDescending(struct NODE *pRoot)
if( pRoot )
if(pRoot->Right) DisplayDescending(pRoot->Right);
printf("9d\t", pRoot->info);
if(pRoot->Left) DisplayDescending(pRoot->Left);
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia, """
@ nitro” pr
‘ofessionalDATA STRUCTURES (CSC-214)
void DeleteTree( struct NODE *pRoot) // This function deletes all nodes in the tree
{
if( pRoot )
{
if(pRoot->Right)
{
DeleteTree(pRoot->Right);
y
if(pRoot->Left)
{
DeleteTree(pRoct- > Left);
+
free pRoot );
}
int main( void )
{
int ch, item;
while( 1)
{ printf("\n\n\n_ Binary Search Tree Functions\n\n");
printf("\ni, Insert a New Node");
printf("\n2, Remove Existing Node");
printf("\n3. In-Order Traverse (Ascending Order)";
printf("\n4, Pre-Order Traverse ");
printf("\n5. Post-Order Traverse ");
printf("\n6. Display in Descending Order (Reverse)");
printf("\n7. Exit”);
printf("\nEnter you choice:
seanf("%od" &ch);
switch(ch)
{
case 1:
printf("\n\n put a number: "); scanf("%od" ,&item);
Insert(item);
break;
case 2:
Wl Remove(); // This function is not defined.
break; // Students shall write this function as home work.
case 3:
printf("\n\n\n In-Order Traverse (ASCENDING ORDER)\n");
In_Order(Root);
printf("\n\n");
break;
case 4:
“= Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia .
@ nitro” professionalDATA STRUCTURES (CSC-214)
printf("\n\n\n Pre-Order Traverse \n");
Pre_Order(Root);
printf("\n\n");
break;
case 5:
printf("\n\n\n Post-Order Traverse \n");
Post_Order(Root);
printf("\n\n");
break;
case 6:
printf("\n\n\nDESCENDING ORDER (Reverse )\n");
DisplayDescending(Root);
printf("\\n");
break;
case 7:
DeleteTree(Root);
exit(0);
default:
printf("\n\nInvalid Input");
3 // end of switch
} // end of while loop
} // end of main( ) function
Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia. "*,
vane @ nitro” professionalDATA STRUCTURES (CSC-214)
Sorti
Sorting and searching are fundamental operations in computer science.
Sorting refers to the operation of arranging data in some given order. Such as
increasing or decreasing, with numeric data or alphabetically, with string data.
Insertion Sort:
Suppose an array A with N elements A[0], A[1], ... . A[N-1] is in memory.
The insertion sort algorithm scan A from A[0] to A[N-1], inserting each element
ALK] into its proper position in the previously sorting sub array A[O], A[1],... ALK-
1]. That is:
Pass 1: A(t] is inserted either before of after A[0] so that: A[0], A[1] is sorted.
Pass 2: A[2] is inserted into its proper place in A[O], A[1], so that A[O], A[1], A[2]
are sorted.
Pass 3: A[3] is inserted into its proper place in A[0], Al 1], Al2] so that: A[O], Al1],
A[2], A[3] are sorted.
A[IN-1] is inserted into its proper place in A[O], Al1], .... . A[N-1] 50
0], A[1],.... A[N-1] are sorted,
This sorting algorithm is frequently used when N is small. There remains only the
problem of deciding how to insert A[K] in its proper place in the subarray A[O], A[1],
+... A[K-1]. This can be accomplished by comparing A[K] with A[K-1], comparing
AIK] with A[K-2], comparing A[K] with A[K-3], and so on, until first meeting an
element Ali] (where i start from k-1) such that Ali] s AIK]. then each of elements
AIK-1], A[K-2], . ... Ali+1] is moved forward one location, and A[K] is then
inserted in the i+1 st position in the array.
pass | “(2b raga) | a2 alsi | ala] | ALS) | Als] | A(7] | ALS)
80 33 44 i 88 22 66 5S
oa
K=1 7 80 13344 i 88 22 66 5S
wy
K=2 33 80 44 11 88 22 66 55
K=3 44 77 80 11 FA 22 66 ss
_, 44. ES
K= i 33 22 66 5S
K=5 i 38 44 77 80 88 22 66 5S
ao
kes fir foo [33 [aa so les |e |ss
ee
K=7 1 22 33 44 ee 7 80 88 3S
K=8 1 22 33 44 5S 66 77 80 88
1 22 33 44 55 66 77 80 88
~~ Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia
@ nitro” professionalDATA STRUCTURES (CSC-214)
The algorithm is simplified iF there always is an element A[i] such that All] = AIK];
other wise we must constantly check to see if we are comparing A[K] with A[0].
Algorithm: (INSERTION SORT) INSERTION (A, N)
[Where A isan array and N is the Size of values in the array ]
1, Repeat steps 2 to 4 for K=1,2,3,
2. Set TEMP = A[K] and | =K-1.
3 Repeat while i >= 0 and TEMP < Afi]
a) Set Al [i]. [Moves element forward.]
b) Seti
[End of loop.
4, Set Ali+1] =TEMP. [Insert element in proper place.]
[End of Step 2 loop.]
5 Return.
2 Ned
/) Programe of Implementation of Insertion SORT
// _ Pxoguanmd by SHAHID LONE
// Insertion Sort
void Insertionsort( int x[],int )+
void main(void)
‘
ta Collection for I
"\niow many value a:
ertion Sort\n";
to Pp. .
ali
Sort ( An)?
\nSORTED' ARRAY\n"s
for( i=07 i < ny its ) Ali]e<\t!
void Insertio
( int i, ky
for(
et( int [100], int ny
) x[i4l] = xLi]e
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia. "*, .
vane @ nitro” professionalDATA STRUCTURES (CSC-214)
Selection Sort:
Suppose an array A with N elements A[O], Alt], . A[N-1] Is in memory. The
Selection sort algorithm for sorting A works as follows. First find the smallest
element in the list and put it in the first position. Then find the second smallest
element in the list and put it the second position. And so on.
Pass 1: Find the location LOC of the smallest in the list of N elements A[O], A[1], «
+. A[N-L], and then interchange A[LOC] and A[0]. Then:
A[0] is sorted.
Pass 2: Find the location LOC of the smallest in the sublist of N-1 elements A[1],
A[2],... A[N-1], and interchange A[LOC] and A[1]. Then
A[O}, Al 4] is sorted. Since A[O] < A[1]
Pass N-1i Find the location LOC of the smallest AIN-2] and A[N-1], and then
interchanged A[LOC] and A[N-1]. Then:
A[O], A[1], A[2],... « A[N-4] is sorted
Algorithm: MIN(A, K, N, LOC)
[An Array A is in memory. This procedure finds the location Loc of the
smallest element among A[K], A[K+1], .. . . .A[N-1].]
1. Set MIN = A[K] and LOC = K, [Initializes pointers.)
2. Repeat for J=K+1, K+2,......N
If MIN > A[J], then: MIN = A[J] and LO
3. Return LOC.
Algorithm: (SELECTION SORT) SELECTION (A, N)
1. Repeat steps 2 and 3 for K=0,1,2,.... . N-2:
2 Call MIN(A, K, N, LOC)
3. [Interchange A[K] and A[LOC].]
Set TEMP = A[K], A[K] = A[LOC] and A[LOC] = TEMP.
[End of step i loop.]
4. Exit
~~ Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia .
@ nitro” pr
‘ofessionalDATA STRUCTURES (CSC-214)
Pass ALO] | A[1] | A(2] | AL3] | AL4] | ALS] | A[6] | A[7]
K=0,LOC=3 |2Z 33 |44 |aa |es (22 |66 | 55
K=1,LOC=5 /11 | 33 | 44 77 | 88
ik
66 | 55
K=2,LOC=5 | 11 | 22 |4@ |77 |88 | 33 |66 |55
K=3,Loc=5 |11 |22 |33 |zz |ss |44 j66 |ss
K=4,LOCe7 | 11 | 22 | 33 ss |77 |66 |55
K=5,LOce6 [11 | 22 | 33 55 | 27 |66 | 88
W
kK=6,LOC=6 /11 | 22 | 33 55 |66 |zz | 88
Eig )e)s
Sorted 11 }22 | 33 55 |66 |77 | 88
Programe of Implementation of Selection SORT
Programed by SHAHID LONE
dude
void Selectionsort( int
int MIN(int [], int):
Jy imtys
void main (void)
( int in?
int "A[ARRAY SIZE];
ction Sort\n";
2\n"7
Or ic ny I++)
SelectionSort (A, n)s
\nSORTED ARRAY\
picns itt)
void SelectionSort( int A[ARRAY,
{int K, loc, temp?
for( K= 0; K< Nel; Ket)
MIN (A, K);
AT]? A[x] = Afloc]; alloc] = temp;}
)
int MIN(int A[ARRAY
(ant min, 3, locy
min = AIK]; lo
for( j = K+l:
if( min > A[}]) (min = ACJ]: L
return locs
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia, 7" .
vane @ nitro” professionalDATA STRUCTURES (CSC-214)
Merging:
Suppose A is sorted list with r elements and B is a sorted list with s elements.
The operation that combine the elements of A and B into a single sorted list C with
n= rts elements is called merging. One simple way to merge is to place the
elements of C after the elements of A and then use some sorting algorithm on the
entire Isit. This method does not take advantage of the fact that A and B are
individually sorted. A much more efficient algorithm is merge sort algorithm.
Suppose one is given two sorted decks of cards. The decks are merged as:
88 55] | El
8 33 8 33
2
33 |,
22
2
(a) (b)
2 | 55 88 55
48
5
44 48
2 3
22 2
38
ss
(e) (d)
44
33
22
te) Divide Comper Combine
Merge Sort:
The merge sort splits the list to be Noreen
sorted into two equal halves, and places ry
them in separate arrays. Each array is ae
recursively sorted, and then merged back
together to form the final sorted list. hargeartaa)
a ke sated .
Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia, 7" .
vane @ nitro” professionalDATA STRUCTURES (CSC-214)
Consider an array then split into two list, then:
Pass 1: S42
Pass 2: sa s
Pass 3: 41s 213
(23 T4 Ts)
Pass 4:
Algorithm: MERGESORT (A, N)
1. IfN=1, Return,
2. Set N1:=N/2, N2
3. Repeat for i=0,1,2
N-NA.
4, Repeat for j=0,1,2
5. Call MERGESORT (L, N1).
6, Call MERGESORT (R, N2).
7. Call MERGE (A, L, Ni, R,N2).
8, Return.
Algorithm: MERGE (A, L, Ni, R, N2)
1. Set
2. Repeat fork=0,1,2..... (N1+N2-1)
If i
include
int mia
32 (lewchigh)
{mide (Low*high) /25
sort (Lowmid) 3
sort (midi, high) +
merge (low,mid, high) ;
low, int mia, int nigh)
iwhile ( (néemid) 66 (j<*high))
(if thl<-alji)
teril=a thls
eb
,
" Getideatsis
ye
ir(nmia)
(Sor (ked keahigh: kt+)
jecil-atel
?
else
(ee (Ieshy econ e+)
qclleatkl:
for (keLowskéshighsit+) alkl=b Ik]
)
void maint)
(ant nom, i7
councetetereeeeee seeeeesee
COuTcettteenseetennnassieenneeeeesnasensscentasniesassensneeessatensetecendl)
counccendl Processes digits from right to left
+ Create groupings of items with same value in specified digit
> Collect in order and create grouping with next significant digit
(ss_[24 J92 [40 }
3 4 5 6
55
Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia
nine © nitro” professionalDATA STRUCTURES (CSC-214)
Algorithm: RADIXSORT (A, N, R)
1. If N=1, then: Return.
2. Set D=R/10, P=-1
3. Repeat for 10,12... . (N-1)
Repeat for j=0,1,2...9
set ¢ [i] [j
i
4. Repeat for i= (N
If m=O, then: Set Z:
iv, Set C [i] [m] = Ail
5. Repeat for j=0,1,2....9
i, Repeat for j=0,1,2.... (N-1)
1. IFC [i] [i] * -1,then:
2. Set P=P+1,
b. Set A [P]=C [i] [i]
6. If Z=1, then
RADIXSORT (A, N, R*10).
7. Return.
C++ Code (RADIX SORT):
“Shahid Iqbal (Lecturer) Computer College
Qassim University Kingdom of Saudi Arabia. "*,
vane @ nitro” professionalDATA STRUCTURES (CSC-214)
TE=RTISRF
if (W>1) obj. radix (1!
3-aispiayo?
Quick Sort(An Application of STACKS):
Let A be a list of n data items “sorting A” refers to the operation of
rearranging the elements of A so that they are in some logical order. Such as
numerically ordered when A contains numerical data, or alphabetically ordered when
A contains character data,
Quick sort is an algorithm of the divide-and-conquer type. That is, the
problem of sorting a set is reduced to the problem of sorting two smaller sets.
Algorithm: QUICKSORT (A, LEFT, RIGHT)
If LEFT 2 RIGHT, then: Return.
Set MIDDLE = PARTITION (A, LEFT, RIGHT)
Call QUICKSORT (A, LEFT, MIDDLE-1).
Call QUICKSORT (A, MIDDLE+1, RIGHT).
Return,
pe ene
Algorithm: PARTITION (A, LEFT, RIGHT)
1, Set X = A[LEFT].
2. Set I = LEFT.
3. Repeat for j = LEFT+1,LEFT+2,..... RIGHT
If Alj] < x, then:
Seti = i+1.
Cali SWAP (ALi), ALj]).
4. Call SWAP (Afi), A[LEFT]. a nitro”™® professional
5, Return i.DATA STRUCTURES (CSC-214)
C++ Code (QUICK SORT):
Sinelude
#include
int conet MAK:
int AIMAKI;
class quick
Ipublic:
void get (0s
void quick sort(int , int);
int particfon(int , ine);
void display();
de
void quick: :gec()
{coutk<"\n\n How many values you want “>
‘Sin>oNr
iE qpyaR)
{cout<<"\n\n \t Maximum number of values is "atile)
i
void quick: :quick sore (i
(ie (ueer>-araun) ree
int mrppuEsparci
guick_sort (L2FT,
quick sore (MID0Ls+
‘on (LEFT, RIGHT) ;
DDLE-1) }
)
REGED)
Soe (int S-Lerr+d;$conzcan3++)
irarlan
taste
int temp=a(i;
int tempealil;
ALLISALLEPT]
AILEFT]=cenp;
?
void quick: display)
telzsce (0%
cout<<"\n\n\n\n\e\t\e\t s:
for(int in
{eout