BIT2203+Data+Structure+and+Algorithms - Lecture Notes From Virtual Directorate
BIT2203+Data+Structure+and+Algorithms - Lecture Notes From Virtual Directorate
Email: [email protected]
Web: www.mku.ac.ke
DEPARTMENT OF INFORMATION
TECHNOLOGY
about:blank 1/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Contents
CHAPTER ONE ............................................................................................................................................... 5
DATA STRUCTURES ................................................................................................................................... 5
What is Linked List? .............................................................................................................................. 25
1.4.1 Pros and Cons of Linked Lists...................................................................................................... 26
1.4.2 What is the good and bad thing about linked list? ....................................................................... 27
1.4.3 Types of linked lists ....................................................................................................................... 27
Linearly linked lists........................................................................................................................... 27
Circularly linked lists ....................................................................................................................... 27
Singly Linked Lists ........................................................................................................................... 27
Doubly linked lists............................................................................................................................. 27
Multiply-linked Lists ........................................................................................................................ 27
Binary Trees ........................................................................................................................................ 34
1.5.4 Traversal methods ....................................................................................................................... 37
CHAPTER TWO ............................................................................................................................................ 41
INFIX AND POSTFIX EXPRESSION (REVERSE POLISH NOTATION) ............................................................ 41
CHAPTER THREE .......................................................................................................................................... 47
CHAPTER FOUR ........................................................................................................................................... 54
SEARCH AND SORT ALGORITHMS ........................................................................................................... 54
SAMPLE EXAMS QUESTIONS ....................................................................................................................... 68
about:blank 2/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
COURSE OUTLINE
WEEK EIGHT
4. Recursive functions
Factorial functions
Power functions
Fibonacci functions
WEEK NINE
5. Postfix and infix expressions
WEEK TEN
6 .Traversal of the tree
Pre-order traversal
In-order traversal
Post-order traversal
about:blank 3/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
WEEK ELEVEN
7. Search
Linear search
Binary search
A sss
se
essm
sm ent
nt ss
Req
equ ired text bo oks
Tex
ext b o oks
ks f orr ffu
ur
rth er readin g
MKlaus W., Algorithms, data structures, programmes, New Delhi, MCGraw Hill
about:blank 4/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
CHAPTER ONE
DATA STRUCTURES
Learning objectives:
By the end of the chapter a student shall be able to:
Understand and Manipulate data structures
Design and apply algorithms to various data structures
Understand the application areas of various data structures
What is an array?
Array is a very basic data structure provided by every programming language. Let’s talk about an
example scenario where we need to store ten employees’ data in our C/C++ program including
name, age and salary. One of the solutions is to declare ten different variables to store employee
about:blank 5/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
name and ten more to store age and so on. Also you will need some sort of mechanism to get
information about an employee, search employee records and sort them. To solve these types of
problem C/C++ provide a mechanism called Arrays.
Definition
An array is simply a number of memory locations, each of which can store an item of data of the
same data type and which are all referenced through the same variable name. Array may be
defined abstractly as finite order set of homogeneous elements. So we can say that there are
finite numbers of elements in an array and all the elements are of same data type. Also array
elements are ordered i.e. we can access a specific array element by an index.
array_type variable_name[array_size];
int Age[10];
Here array_type declares base type of array which is the type of each element in array. In our
example array_type is int and its name is Age. Size of the array is defined by array_size i.e. 10.
We can access array elements by index, and first item in array is at index 0. First element of
array is called lower bound and its always 0. Highest element in array is called upper bound.
In C programming language upper and lower bounds cannot be changed during the execution of
the program, so array length can be set only when the program in written.
Age 0 Age 1 Age 2 Age 3 Age 4 Age 5 Age 6 Age 7 Age 8 Age 9
30 32 54 32 26 29 23 43 34 5
Note: One good practice is to declare array length as a constant identifier. This will minimise the
required work to change the array size during program development.
#define NUM_EMPLOYEE 10
about:blank 6/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Go to course
CHAP 2 - Summary
about:blank 7/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
int Age[NUM_EMPLOYEE];
Initialisation of array is very simple in c programming. There are two ways you can initialise
arrays.
Look at the following C code which demonstrates the declaration and initialisation of an array.
Age [0]=30;
Age [1]=22;
Age [2]=33;
Age [3]=44;
Age [4]=25;
Array can also be initialised in a ways that array size is omitted, in such case compiler
automatically allocates memory to array.
Let’s write a simple program that uses arrays to print out number of employees having salary
more than 3000.
Array in C Programming
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_EMPLOYEE 10
about:blank 8/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
scanf("%d",&Salary[i]);
if(Salary[i]<3000)
lCount++;
else
gCount++;
getchar();
return 0;
about:blank 9/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
#include <cstdlib>
#include <iostream>
#define NUM_EMPLOYEE 10
cout << "Enter employee salary (Max 10) " << endl;
cout << "Enter employee salary: - " << i+1 << endl;
if(Salary[i]<3000)
lCount++;
else
gCount++;
cout << "There are " << gCount << " employee with salary more than 3000" << endl
<< "There are " << lCount << " employee with salary less than 3000" << endl;
system("PAUSE");
return EXIT_SUCCESS;
about:blank 10/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Often there is need to manipulate tabular data or matrices. For example if employee salary is
increased by 20% and you are required to store both the salaries in your program. Then you will
need to store this information into a two dimensional arrays. C/C++ gives you the ability to have
arrays of any dimension.
Consider the example above, you have to store, previous salary, present salary and amount of
increment. In that case you will need to store this information in three dimensional arrays.
First I will show you how to declare a two dimensional array and initialise it. Then write a
complete program to use multidimensional arrays.
int Salary[10][2];
This defines an array containing 10 elements of type int. Each of these elements itself is an array
of two integers. So to keep track of each element of this array is we have to use two indices. One
is to keep track of row and other is to keep track of column.
Here is a graphical view of multidimensional array that we use to store salary and increment on
salary. First column stores the salary element of the array and second column stores increment on
salary. We could add another column to store the new salary which adds the increment to the
salary.
Column 0 – Column 1 –
Salary Increment
Row 0
Row 2
Row 3
about:blank 11/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Row 4
Row 5
Row 6
Row 7
Row 8
Row 9
Row 10
Multidimensional arrays can also be initialised in two ways just like one dimensional array. Two
braces are used to surround the row element of arrays.
If you are initialising more than one dimension then you will have to use as many braces as the
dimensions of the array are.
{2300, 460},
{3400, 680},
{3200, 640},
{1200, 240},
{3450, 690}
};
int Salary [5][2] ={0}; //This will initialise all the array elements to 0
Salary [0][0]=2300;
Salary [1][0]=3400;
about:blank 12/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Salary [2][0]=3200;
Salary [3][0]=1200;
Salary [4][0]=3450;
Salary [0][1]=460;
Salary [1][1]=680;
Salary [2][1]=640;
Salary [3][1]=240;
Salary [4][1]=690;
Here is a complete program written in both C and C++ to demonstrate the use of
multidimensional arrays.
The code below demonstrates two dimension arrays. It uses the same example of employee
salary to increment it by 20% and adds it to actual salary then print current salary, increment and
new salary.
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_EMPLOYEE 10
int Salary[NUM_EMPLOYEE][2]={
{2300,0},
{3400,0},
about:blank 13/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
{3200,0},
{1200,0},
{3450,0},
{3800,0},
{3900,0},
{2680,0},
{3340,0},
{3000,0}
};
int lCount=0,gCount=0,i=0;
Salary[i][1] = ((Salary[i][0]*20)/100);
printf("%d\t\t%d\t\t%d\n",Salary[i][0],Salary[i][1],Salary[i][0]+Salary[i][1]);
getchar();
return 0;
#include <cstdlib>
about:blank 14/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
#include <iostream>
#define NUM_EMPLOYEE 10
int Salary[NUM_EMPLOYEE][2]={
{2300,0},
{3400,0},
{3200,0},
{1200,0},
{3450,0},
Two of the more common data objects found in computer algorithms are stacks and queues. Both
of these objects are special cases of the more general data object, an ordered list.
A stack is an ordered list in which all insertions and deletions are made at one end, called the top.
A queue is an ordered list in which all insertions take place at one end, the rear, while all
deletions take place at the other end, the front. Given a stack S=(a[1],a[2],.......a[n]) then we say
that a1 is the bottommost element and element a[i]) is on top of element a[i-1], 1<i<=n. When
viewed as a queue with a[n] as the rear element one says that a[i+1] is behind a[i], 1<i<=n.
about:blank 15/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
The restrictions on a stack imply that if the elements A,B,C,D,E are added to the stack, n that
order, then th efirst element to be removed/deleted must be E. Equivalently we say that the last
element to be inserted into the stack will be the first to be removed. For this reason stacks are
sometimes referred to as Last In First Out (LIFO) lists.
Is a data structure that utilizes the concept of last in First Out (LIFO)
1. Plates in a cafeteria
3. Number conversion
4. Program execution
about:blank 16/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
If the top = = 0
1) Increment top by 1
Decrease top by 1
Class stack
Int top;
Int stackarray[50];
Public:
Stack( );
Int emptystack( );
Int fullstack( );
};
Example1
Using stack structure write a program for displaying numbers in the reverse order
Solution
about:blank 17/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Int top;
Int stackarray[maxsize];
Public:
Int emptystack( );
Int fullstack( );
};
Stack : : stack( )
Top = 0;
Return top = = 0;
about:blank 18/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Top + + ;
Item = stackarray[top]
top - -;
void main( )
Stack S;
Int i,n,x;
cin>>n;
{ cin>>x;
s.push(x);
While (! S . emptystack( ))
about:blank 19/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
S . pop (x);
cout <<x<<”\n”;
Algorithm
i)Compute remainder
ii)Push remainder into the stack
iii)Compute next number (the quotient become the next number)
4) Display the content of stack((pop)
Example 2
Using stack, write a program for converting a number from base 10 to any other base (1-9)
Solution
# include <iostream.h>
{
class stack
Int top;
Int stackarray(maxsize)
about:blank 20/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Public:
Stack ( );
Int emptystack( );
Int fullstack( );
Top = 0;
}
int stack : : emptystack ( )
{
Return top = = 0;
}
Int stack: : fullstack ( )
{return top = = max size;
}
Void stock : : push (int item)
{
Top ++;
Stakarray (top) = item;
}
Void stock : : pop (int pitem)
{
Item = stackrray (top);
Top = - ;
}
Void main( )
about:blank 21/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
{
Stalk s ;
Int n ; // number
Int btest ; // base to convert to
{
Remainder= n % btest;
s.push (remainder);
n=n /btest;
}
While (! S.empty stack (j )
{
S.Pop (remainder);
Count << remainder << “ “;
about:blank 22/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
The cafeteria line is one type of queue. Queues are often used in programming networks,
operating systems, and other situations in which many different processes must share resources
such as CPU time.
Queue is a data structure that utililizes the concept of first-in-First Out (FIFO)
Inserting takes place at the rear and deleting takes place at the front
In a circular queue we need a counter that keep track of the the of element in a queue.
We need a generalised approach to compute the rear and the front position;
Rear =(rear +1)% maxsize,
Front = (front + 1) % maxsize
When inserting for the very first time, we need to adjust in position of front from zero to 1.
about:blank 23/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
{
Int rear,front,count;
Int queuearry [maxisize];
Public:
Queue ( );
int fullqueue ( );
Void insertqueue (int item)
front = 0;
count = 0;
}
In’t Queue : : emptyqueue ( )
{
Return count count = =0;
}
Int Queue : : full quarter ( )
{
Return count = = maxsize;
}
Void Queue : : interqueue (int item)
{
If (count = = 0)
Front + +;
about:blank 24/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Example 1
Using Queue structure, write a program for displaying numbers in the same order of insetion
Solution
about:blank 25/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
A linked list is a data structure that consists of a sequence of data records such that in each
record there is a field that contains a reference (i.e., a link) to the next record in the sequence.
The linked list is a useful data structure that can dynamically grow according to data storage
requirements. This is done by viewing data as consisting of a unit of data and a link to more units
of data. Linked list is useful in the implementation of dynamic arrays, stacks, strings and sets.
The link list is the basic ADT in some languages, for example, LISP.
Linked lists are most useful in environments with dynamic memory allocation. With dynamic
memory allocation dynamic arrays can grow and shrink with less cost than in a static memory
allocation environment. Linked lists are also useful to manage dynamic memory environments.
Dramatically a linear linked list can be viewed as follows:
about:blank 26/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Each data element has an associated link to the next item in the list. The last item in the list has
no link. The first element of the list is called the head , the last element is called the tail.
Linked lists can be implemented in most languages. Languages such as Lisp and Scheme have
the data structure built in, along with operations to access the linked list. Procedural languages,
such as C, or object-oriented languages, such as C++ and Java, typically rely on mutable refer-
ences to create linked lists.
Linked lists overcomes all the major limitations of arrays such as:
The size of array is fixed. Though it can be deferred until the array is created at runtime,
but after that it remains fixed.
If you allocate a large space for arrays, the most of the space is really wasted. In case of
small arrays declared, the code breaks in instances when more data elements are used
than array size.
Inserting new elements in the front is potentially expensive because existing elements
need to be shifted over to make room
Linked lists have their own strengths and weakness, but they happen to be strong where arrays
are weak. The array’s features all follow from its strategy of allocating the memory for all its ele-
ments in one block of memory. Linked lists use an entirely different strategy. Linked lists allo-
cate memory for each element separately and only when necessary. [Linked List Basic by By
Nick Parlante]
about:blank 27/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
A user does not have to declare the size of the linked list at the beginning of the program – you
can add and remove objects from the list by merely unlinking them. In addition you can sort the
members of a linked list – without actually moving data objects around – by changing the links.
The cost of flexibility in linked list is speed of access. You can’t just reach in and grab the tenth
element, for example, like you would in case of an array. Instead, you have to start at the begin-
ning of the list and link ten times from one object to the next.
1.4.2 What is the good and bad thing about linked list?
The good thing about linked list is its runtime expandability. Unlike arrays, linked lists are much
flexible in dynamically allocating space for data.
The bad thing about linked lists is its difficulty in accessing an object at random – you can’t just
reach and grab the element.
In linearly linked lists the last node of a list contains a null reference to indicate it as tail or end
of list. This type of lists are also called open linked list.
In circular linked list the last node of a list contains a reference to the first node of the list. These
lists are also called circular lists.
In doubly linked lists, each node contain a link to the next node and yet another to link to previ-
ous node. The two links may be called forwards and backwards or next and previous.
Multiply-linked Lists
In multiply-linked list, each node contains two or more link fields, each field being used to con-
nect the same set of data records in a different order.
about:blank 28/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
A node is a structure with two parts. One part stores the addresses of the next node.
In a linked list they also have a special node referred to as the head. This node has only
the information as to where the link structure starts.
The last node in a linked list always point to NULL (Zero i.e. nothing)
Let the link of the new node points to the position where the node at the insertion
points was pointing.
Add information
about:blank 29/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Let the link of the previous node points to the link of the previous node points to the
link of the node to be deleted
Free space
1.4.9 Example: Using the linked list concept, write a program for manipulating a stack
#include <;ostream.h>
Class linkedstack
{
Private:
Structure linkedstacknode*link;
Linkedstacknode (int &item,Linked stackNode*head = NULL)
{
Data =item;
Link = head;
}
}
Linked stack Node* Top;
Public:
about:blank 30/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Linked stack ( )
{
TOP = NULL;
}
}
Void linkedstock : : push (int item)
{
Top = new linked stacknode (item,top);
}
Linkedstack s;
Int x, n;
about:blank 31/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Return0;
}
Example: Using the link list concept, write a program for manipulating a queue structure.
Include < iostream .h>
Data = item;
Link = nodelinke;
}
about:blank 32/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
};
LinkedQueuenode*rear,*front;
Public:
LinkedQueue
Front = NULL;
Rear = NULL;
Int emptyQueue ( )
If(front = = NULL)
From = rear;
Else
Front = rear;
Else
about:blank 33/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Void delete(intlitem)
Ptr =front;
Item=front ->data;
Delete ptr;
};
Main c )
{ Inti,x,n;
LinkedQueue Q;
Q.add Q(x);
about:blank 34/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Q. DeleteQ(x)
Return O;
Binary Trees
The simplest form of tree is a binary tree. A binary tree consists of
about:blank 35/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
A binary tree
The nodes at the lowest levels of the tree (the ones with no sub-trees) are called leaves.
1. the keys of all the nodes in the left sub-tree are less than that of the root,
2. the keys of all the nodes in the right sub-tree are greater than that of the root,
3. the left and right sub-trees are themselves ordered binary trees.
Insertion
Deletion
about:blank 36/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
1.5.2 Algorithm
Algorithm
2. If X is a leaf, delete X
Observation
about:blank 37/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
about:blank 38/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Stepping through the items of a tree, by means of the connections between parents and children,
is called walking the tree, and the action is a walk of the tree. Often, an operation might be
performed when a pointer arrives at a particular node. A walk in which each parent node is
traversed before its children is called a pre-order walk; a walk in which the children are
traversed before their respective parents are traversed is called a post-order walk; a walk in
which a node's left subtree, then the node itself, and then finally its right subtree are traversed is
called an in-order traversal. (This last scenario, referring to exactly two subtrees, a left subtree
and a right subtree, assumes specifically a binary tree.)
about:blank 39/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
a. Stores name
about:blank 40/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
REVIEW QUESTIONS
1. Using C++, write a program that implements algorithm for inserting data elements
into one dimensional array
3. Write a C++ program that implements the algorithms for pushing, popping and
deleting data elements from the stack data structure
4. Illustrate how queue data structure is different from stack data structure
5. Construct a binary tree and apply the three traversal techniques on the following
expression (A+B)*(C-D)
6. Discuss the concept of graph data structure
FURTHER READING
Salamis S, Data structures, Algorithms and application in Java, McGraw Hill
about:blank 41/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
CHAPTER TWO
Learning objectives:
By the end of the chapter a student shall be able to:
Understand and apply the algorithm in converting infix to postfix expression
If the scannned character is an operand, add it to the Postfix string. If the scanned
character is an operator and if the stack is empty Push the character to stack.
If the scanned character is an Operand and the stack is not empty, compare the
precedence of the character with the element on top of the stack (topStack). If topStack
has higher precedence over the scanned character Pop the stack else Push the scanned
character to stack. Repeat this step as long as stack is not empty and topStack has
precedence over the character.
about:blank 42/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
(After all characters are scanned, we have to add any character that the stack may have
to the Postfix string.) If stack is not empty add topStack to Postfix string and Pop the
stack. Repeat this step as long as stack is not empty.
Example:
Let us see how the above algorithm will be imlemented using an example.
Initially the Stack is empty and our Postfix string has no characters. Now, the first
character scanned is 'a'. 'a' is added to the Postfix string. The next character scanned is
'+'. It being an operator, it is pushed to the stack.
Postfix String
Stack
Next character scanned is 'b' which will be placed in the Postfix string. Next character
is '*' which is an operator. Now, the top element of the stack is '+' which has lower
precedence than '*', so '*' will be pushed to the stack.
Postfix String
Stack
about:blank 43/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Infix Expression:
Postfix Expression:
Postfix Evaluation:
In normal algebra we use the infix notation like a+b*c. The corresponding postfix
notation is abc*+. The algorithm for the conversion is as follows :
If the scannned character is an operand, add it to the stack. If the scanned character is
an operator, there will be atleast two operands in the stack.
If the scanned character is an Operator, then we store the top most element of the
stack(topStack) in a variable temp. Pop the stack. Now evaluate
topStack(Operator)temp. Let the result of this operation be retVal. Pop the stack and
Push retVal into the stack.
After all characters are scanned, we will have only one element in the stack. Return
topStack.
Example :
Let us see how the above algorithm will be imlemented using an example.
Initially the Stack is empty. Now, the first three characters scanned are 1,2 and 3,
which are operands. Thus they will be pushed into the stack in that order.
about:blank 44/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Expression
Stack
Next character scanned is "*", which is an operator. Thus, we pop the top two elements from the
stack and perform the "*" operation with the two operands. The second operand will be the first
element that is popped.
Expression
Stack
The value of the expression(2*3) that has been evaluated(6) is pushed into the stack.
Expression
Stack
Next character scanned is "+", which is an operator. Thus, we pop the top two elements from the
stack and perform the "+" operation with the two operands. The second operand will be the first
element that is popped.
Expression
Stack
The value of the expression(1+6) that has been evaluated(7) is pushed into the stack.
about:blank 45/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Expression
Stack
Expression
Stack
Next character scanned is "-", which is an operator. Thus, we pop the top two elements from the
stack and perform the "-" operation with the two operands. The second operand will be the first
element that is popped.
Expression
Stack
The value of the expression(7-4) that has been evaluated(3) is pushed into the stack.
Expression
Stack
Now, since all the characters are scanned, the remaining element in the stack (there will be only
one element in the stack) will be returned.
End result :
about:blank 46/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
REVIEW QUESTIONS
FURTHER READING
about:blank 47/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
CHAPTER THREE
RECURSIVE FUNCTIONS
Learning objectives:
By the end of the chapter a student shall be able to understand and write the algorithms of:
Factorial function
Power function
Fibonacci function
These are functions that call themselves i.e self referencing functions
-factorial function
-fibonacci sequence
-power function
4:=4x3x2x1 =24
4x3;
4x3x2;
about:blank 48/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
4x3x2x1;
= 4(4-1)!
n: =n* (n-1) !
Example 1
Write a program for computing factorial of positive numbers using recursive functions.
Solu
Void main ( )
Int x;
Cin>>x.
If (n<1;
Else
Return 1;
about:blank 49/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
1,1,2,3,5,8,13,21,34,55,89,144
=1 + 1
#include iostream.h>
Void main( )
Int I,n,
cout < < “In Enter the nth term of the sequence”;
cout>>n:
about:blank 50/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Return 1;
Else
Solution
Void main ( )
Int x,n;
Cin >>x;
Cin >.n;
If (n= =0)
Return I;
about:blank 51/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Else
Version 2
Class powers
Int x,n;
Int ans;
Public :
};
X =a;
N = b;
If (b = = 1)
ans =1;
Else
about:blank 52/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Void main ( )
POWERS P;
Int y,z;
p.computerpower (y,z)
Version 3
# include <iostream.h>
C:n>>x;
Cin >>n
If (n = = 0)
ans = 1;
Else
about:blank 53/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Void main ( )
POWERS P;
p. getpowerva.ines( );
p.computerpower( );
REVIEW QUESTIONS
FURTHER READING
Salamis S, Data structures, Algorithms and application in Java, McGraw Hill
about:blank 54/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
CHAPTER FOUR
Learning objectives:
By the end of the chapter a student shall be able to understand and apply the:
Linear search and binary search algorithms
Bubble, insertion, selection and quick sort algorithms to data structures
4.1 SEARCHING
Looking for data /information stored in a structure, array, file,etc
A linear search looks down a list, one item at a time, without jumping. In complexity terms
this is an O(n) search - the time taken to search the list gets bigger at the same rate as the list
does. Linear involves comparing data element to find
As an example, suppose you were looking for U in an A-Z list of letters (index 0-25; we're
looking for the value at index 20).
about:blank 55/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Create a structure
Insert elements
Set a loop
Example
Solution
#include <iostream.h>
Void main ( )
Int I ;
Int n;
Int x;
about:blank 56/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Cin>>x;i=1;
While (i< = n)
Break;
Else
I ++;
If(i>n)
Example2
#include <iostream.h>
int main()
{
const int NUMEL = 10;
int nums[NUMEL] = {5,10,22,32,45,67,73,98,99,101};
int item, location;
cout << "Enter the item you are searching for: ";
cin >> item;
about:blank 57/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
return 0;
}
return -1;
}
A binary search is when you start with the middle of a sorted list, and see whether that's
greater than or less than the value you're looking for, which determines whether the value is in
the first or second half of the list. Jump to the half way through the sublist, and compare again
etc. This is pretty much how humans typically look up a word in a dictionar y (although we
use better heuristics, obviously - if you're looking for "cat" you don't start off at "M"). In
complexity terms this is an O(log n) search - the number of search operations grows more
slowly than the list does, because you're halving the "search space" with each operation.
Utilizes the concept of divide and conquer. It assume that the data element are sorted out. It
addresses the limitation of linear search.
about:blank 58/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Compare list[12] ('M') with 'U': Smaller, look further on. (Range=13-25)
Compare list[19] ('T') with 'U': Smaller, look further on. (Range=20-25)
Compare list[22] ('W') with 'U': Bigger, look earlier. (Range=20-21)
Compare list[20] ('U') with 'U': Found it! Finished.
3) Create a structure
6) Initialize top to 1
ii. compare search key with the element at the mid position; if found stop searching
Else
iii. if search key < element at mid position adjust bottom position, say mid-1
Example
4,9,11,13,16,20,28
Step1
Top=1
Bottom = 7
Mid = (1+7)/2
about:blank 59/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Step 2
Top = mid +1
= 4+1
=5
Bottom = 7
Mid = (7+5)/2
=6
Example
Write a paragram for searching data elements using binary search technique.
Solution
Void main ( )
Int I,n,x;
Int top,bottom,mind;
Cin>>n;
Cin>>x;
Top = 1;
Bottom = n;
about:blank 60/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
If (x = = list [mid])
Break;
Else
If (x<list [mid] )
Bottom = mid – 1;
Else
Top = mid + 1;
If (top >bottom)
Binary search requires the input data to be sorted; linear search doesn't
Binary search requires an ordering comparison; linear search only requires equality
comparisons
Binary search has complexity O(log n); linear search has complexity O(n) as discussed
earlier
Binary search requires random access to the data; linear search only requires sequential
access (this can be very important - it means a linear search can stream data of arbitrary
size)
about:blank 61/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Compare each element (except the last one) with its neighbor to the right
Compare each element (except the last two) with its neighbor to the right
The last two elements are now in their correct and final places
Compare each element (except the last three) with its neighbor to the right
about:blank 62/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
The outer loop is executed n-1 times (call it n, that’s close enough)
Each time the outer loop is executed, the inner loop is executed
Inner loop executes n-1 times at first, linearly dropping to just once
On average, inner loop executes about n/2 times for each execution of the outer loop
In the inner loop, the comparison is always done (constant time), the swap might be done
(also constant time)
about:blank 63/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
Loop invariants
Oddly enough, what is usually most important in understanding a loop is finding an invariant:
that is, a condition that doesn’t change
In bubble sort, we put the largest elements at the end, and once we put them there, we don’t
move them again
The variable outer starts at the last index in the array and decreases to 0
Our invariant is: Every element to the right of outer is in the correct place
That is, for all j > outer, if i < j, then a[i] <= a[j]
When this is combined with outer == 0, we know that all elements of the array are in the
correct place
about:blank 64/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
The selection sort might swap an array element with itself--this is harmless, and not worth
checking for
Analysis:
The inner loop executes about n/2 times on average (from n to 2 times)
Work done in the inner loop is constant (swap two array elements)
about:blank 65/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
// Invariant: for all i, if outer <= i <= inner, then a[min] <= a[i]
}
This loop searches through the array, incrementing inner from its initial value of outer+1 up to
a.length-1
As the loop proceeds, min is set to the index of the smallest number found so far
Each time through the loop, the minimum remaining value is put in a[outer]
The invariant is that all the elements to the left of outer are sorted with respect to one another
For all i < outer, j < outer, if i < j then a[i] <= a[j]
This does not mean they are all in their final correct place; the remaining array elements ma y
need to be inserted
about:blank 66/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
When we increase outer, a[outer-1] becomes to its left; we must keep the invariant true by
inserting a[outer-1] into its proper place
This means:
Making room for the inserted element (by shifting over other elements)
We run once through the outer loop, inserting each of n elements; this is a factor of n
Hence, the time required for an insertion sort of an array of n elements is proportional to n2/4
Summary
Bubble sort, selection sort, and insertion sort are all O(n2)
about:blank 67/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
As we will see later, we can do much better than this with somewhat more complicated
sorting algorithms
Within O(n2),
Bubble sort is very slow, and should probably never be used for anything
Insertion sort is usually the fastest of the three--in fact, for small arrays (say, 10 or 15
elements), insertion sort is faster than more complicated sorting algorithms
Selection sort and insertion sort are “good enough” for small arrays
REVIEW QUESTIONS
FURTHER READING
Salamis S, Data structures, Algorithms and application in Java, McGraw Hill
MKlaus W., Algorithms, data structures, programmes, New Delhi, MCGraw Hill
about:blank 68/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
QUESTION ONE
i. data type
ii. Abstract data type (ADT)
iii. Pointers
iv. Data structure
(4 marks)
b) For each of the following situations, which of these ADT''s (1 through 4) would
be most appropriate:
i. a queue,
ii. a stack,
iii. a list,
iv. none of these?
i. The customers at a Kenchicken's counter who take numbers to make their
turn
ii. Integers that need to be sorted
iii. Arranging plates in the cafeteria
iv. People who are put on hold when they call Kenya Airways to make
reservations
v. Converting infix to postfix expression
(5 marks)
c) Explain why a test for an empty stack must be carried out when performing
stack operations. Write a procedure/ function for the function EMPTY of a stack
identifier
(4 marks)
about:blank 69/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
d) I) If you push the letters A, B, C and D in order onto a stack of characters and
then POP them , in what order will they be deleted from the stack
(2 marks)
ii) Represent the following expression as binary tree and write prefix and postfix
form of the expression
(A+B+C*D)-(A/B-CD+E)
(4 marks)
(2 marks)
(3 marks)
g) State and define all the possible operations on a stack data structure
(6 marks)
QUESTION TWO
a) Describe how deletion of a node in between the linked list can be carried out
illustrated your answer with a diagram
( 5 marks)
b) Beginning with an empty binary search tree what binary search tree is formed
when you insert the following values in the order
i. W,T,N,J,E,B,A
ii. A,B,W,J,N,T,E
(4 marks)
about:blank 70/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
(1 mark)
iii) Each element of a doubly linked structure has three fields. State the three
fields illustrating your answer with a diagram
(2 marks)
QUESTION THREE
a) Convert the following infix arithmetic expression into its equivalent reverse
polish form
i. A+B*C
ii. (A+B)*C
iii. A/CB-(C+D)*(E-A)*C
iv. A/B-C+D*E+A+C
(4 marks)
b) Use stack to evaluate the postfix expression ABC+D*+E+. Show the status of
the stack after each step of the algorithm. Assume the following values for the
identifiers: A=8, B=5, C=3, D=9, E=4.
(4 marks)
c) i)Suppose that the vowels form a tree with “O” as the root and its children are
“U”, “I”,”A”, left-to-right and “E” is the only child of “I”. Reconstruct this tree as a
binary tree
(3 marks)
about:blank 71/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
ii) Trace the bubble sort algorithm as it sort the following array into ascending
order:
20 80 40 25 60 30
(2 marks)
d) Write an algorithm for converting Numbers from Base 10 to any other given base.
Use an example program to implement the algorithm
( 7 marks)
QUESTION FOUR
(5 marks)
(2 marks)
iii) Using quicksort technique sort the following data elements. Use diagrams
to trace the algorithm
QUESTION FIVE
50 70 25 90 30 55 25 15 25
(3 marks)
about:blank 72/73
9/26/23, 8:53 AM BIT2203+Data+Structure+and+Algorithms - Lecture Notes from…
ii) Using the above information trace the algorithm for deleting node 30
(6 marks)
iii) Using the linked list concept, write a program for manipulating a Queue
structure
(11 marks)
about:blank 73/73