3rd Sem Data Structure & Algorithm
3rd Sem Data Structure & Algorithm
Algorithm
Ved Parkash
Associate Professor, CSE
A computer program is a collection of instructions to
perform a specific task. For this, a computer program
may need to store data, retrieve data, and perform
computations on the data.
Data Structure is a way of collecting and organising data
in such a way that we can perform operations on these
data in an effective way. For example, we have some data
which has, player's name "Virat" and age 26. Here "Virat"
is of String data type and 26 is of integer data type.
We can organize this data as a record like Player record,
which will have both player's name and age in it. Now we
can collect and store player's records in a file or database
as a data structure. For example: "Dhoni" 30, "Gambhir"
31, "Sehwag" 33
In simple language, Data Structures are structures
programmed to store ordered data, so that various
operations can be performed on it easily. It represents
the knowledge of data to be organized in memory. It
should be designed and implemented in such a way
that it reduces the complexity and increases the
efficiency.
As we have discussed above, anything that can store
Linear
In Linear data structures,the data items are arranged in a linear sequence.
Example: Array
Non-Linear
In Non-Linear data structures,the data items are not in sequence.
Example: Tree, Graph
Homogeneous
In homogeneous data structures,all the elements are of same type. Example: Array
Non-Homogeneous
In Non-Homogeneous data structure, the elements may or may not be of the same
type. Example: Structures
Static
Static data structures are those whose sizes and structures associated memory
locations are fixed, at compile time. Example: Array
Dynamic
Dynamic structures are those which expands or shrinks depending upon the program
need and its execution. Also, their associated memory locations changes.
Example: Linked List created using pointers
What is an Algorithm ?
An algorithm is a finite set of instructions or logic, written in
order, to accomplish a certain predefined task. Algorithm is not
the complete code or program, it is just the core logic(solution)
of a problem, which can be expressed either as an informal
high level description as pseudocode or using a flowchart.
Every Algorithm must satisfy the following properties:
Input- There should be 0 or more inputs supplied externally to
the algorithm.
Output- There should be atleast 1 output obtained.
well defined.
Finiteness- The algorithm should have finite number of steps.
correct output.
Data structures are used to hold data while algorithms
are used to solve the problem using that data.
An algorithm is said to be efficient and fast, if it takes
less time to execute and consumes less memory space.
The performance of an algorithm is measured on the
basis of following properties :
Time Complexity
Space Complexity
Space Complexity
Its the amount of memory space required by the algorithm,
during the course of its execution. Space complexity must be
taken seriously for multi-user systems and in situations where
limited memory is available.
unambiguous.
Algorithms should be most effective among many
In this case, variables get allocated In this case, variables get allocated only if
permanently your program unit gets active
It uses the data structure called stack for It uses the data structure called heap for
implementing static allocation implementing dynamic allocation
As it can be seen that the length (size) of the array above made is 9. But what if
there is a requirement to change this length (size). For Example,
If there is a situation where only 5 elements are needed to be entered in this
array. In this case, the remaining 4 indices are just wasting memory in this array.
So there is a requirement to lessen the length (size) of the array from 9 to 5.
Take another situation. In this, there is an array of 9 elements with all 9 indices
filled. But there is a need to enter 3 more elements in this array. In this case 3
indices more are required. So the length (size) of the array needs to be changed
from 9 to 12.
This procedure is referred to as Dynamic Memory Allocation in C.
malloc()
Syntax : ptr=(cast-type*)malloc(byte-size)
eg. ptr = (int *)malloc(100 * sizeof (int));
calloc()
Syntax : ptr=(cast-type*)calloc(n,element-size);
Why does malloc() return a void*?
syntax : free(ptr);
This statement cause the space in memory pointer by ptr to
be deallocated.
realloc()
Syntax: ptr=realloc(ptr,newsize);
Here, ptr is reallocated with size of newsize.
Stack
A stack is an Abstract Data Type (ADT), commonly used
in most programming languages. It is named stack as it
behaves like a real-world stack, for example – a deck of
cards or a pile of plates, etc. At any given time, we can
only access the top element of a stack.
This feature makes it LIFO data structure. LIFO stands for
Last-in-first-out. Here, the element which is placed
(inserted or added) last, is accessed first. In stack
terminology, insertion operation is
called PUSH operation and removal operation is
called POP operation.
Push Operation
The process of putting a new data element onto stack is
known as a Push Operation. Push operation involves a
series of steps −
Step 1 − Checks if the stack is full.
Step 2 − If the stack is full, produces an error and exit.
Step 3 − If the stack is not full, increments top to point
at which top is pointing.
Step 4 − Decreases the value of top by 1.
Step 5 − Returns success.
POP (STACK, TOP, ITEM)
This procedure delete the top element of STACK and
assign it to the variable ITEM.
in expression.
Infix Notation
We write expression in infix notation, e.g. a - b + c,
2 (a + b) ∗ c ∗+abc ab+c∗
3 a ∗ (b + c) ∗a+bc abc+∗
5 (a + b) ∗ (c + d) ∗+ab+cd ab+cd+∗
A * [B D +] / E – F * ( G + [H K /] )
[A B D + *] / E – F * [ G H K / +]
[A B D + * E /] – [F G H K / + *]
[A B D + * E / F G H K / + * -]
Algorithm for Evaluation of postfix expression:
This algorithm finds the VALUE of arithmetic expression P written
in postfix notation.
1. Add a right parenthesis “)” at the end of P. [This act as a sentinel]
2. Scan P from left to right and repeat step 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 element of STACK, where A is the top
element and B is the next-to-top element.
(b) Evaluate B Ꚛ A
© place the result of (b) on STACK.
[end of If structure]
[end of step 2 loop]
5. Set VALUE equal to the top element on STACK.
6. Exit.
P: 5, 6, 2, +, *, 12, 4, /, -
P: 5, 6, 2, +, *, 12, 4, /, -, )
Symbol Scanned STACK
5 5
6 5, 6
2 5, 6, 2
+ 5, 8
* 40
12 40, 12
4 40, 12, 4
/ 40, 3
- 37
)
Conversion infix to postfix using stack:
Q: A + ( B * C – ( D / E ^ F ) * G ) * H
LOWER: 1 UPPER: 4
(Quicksort) This algorithm sort an array A with N
elements.
Step 1: [Initialize] TOP=NULL
Step 2: [Push boundary values of A onto stacks when A
has 2 or more elements.]
If N>1, then: TOP=TOP+1, LOWER [1] =1, UPPER[1] = N
Step 3: Repeat step 4 to 7 while TOP != NULL
Step 4: [Pop sublist from stacks]
Set BEG=LOWER[TOP], END=UPPER[TOP]
TOP=TOP-1
Step 5: Call QUICK(A,N,BEG,ENG,LOC)
Step 6: [Push left sublist onto stacks when it has 2 or
more elements]
If BEG < LOC – 1, THEN:
TOP=TOP + 1, LOWER[TOP] = BEG,
UPPER[TOP]=LOC – 1.
[End of If]
Step 7 [Push right sublist onto stacks when it has 2 or
more elements]
If LOC + 1 < END, then:
Top=Top + 1, LOWER[TOP]=LOC+1,
UPPER[TOP]=END.
[End of If]
[End of step 3 loop]
Step 8 Exit.
QUICK(A, N, BEG, END, LOC)
Here A is an array with N elements. Parameters BEG and
END contains the boundary values of the sublist of A to
which this procedure applies. LOC keep track of the
position of the first element A[BEG] of the sublist
during the procedure. The local variables LEFT and
RIGHT will contain the boundary values of the list of
elements that have not been scanned.
1. [initialize] Set LEFT:=BEG, RIGHT:=END AND LOC=BEG.
2. [Scan from right to left]
(a) Repeat while A[LOC]<=A[RIGHT] and LOC !=RIGHT:
RIGHT:=RIGHT – 1
[END of loop]
(b) If LOC=RIGHT, THEN: Return
© If A[LOC]>A[RIGHT], then:
(i) [Interchange A[LOC] and A[RIGHT]]
TEMP:=A[LOC], A[LOC]:=A[RIGHT]
A[RIGHT]:=TEMP
(ii) Set LOC:=RIGHT
(iii) Go to step 3
[End of If structure]
3. [Scan from Left to right]
Types of Deque:
Input Restricted Deque
equal to -1.
Else we decrement rear. But we have to keep in mind
Priority queues:
A priority queue is a collection of elements such that each element
has been assigned a priority and such that the order in which
elements are deleted and processed comes from the following rules:
1. An element of higher priority is processed before any element of
lower priority.
2. Two elements with the same priority are processed according to the
order in which they were added to the queue.
A prototype of a priority queue is a timesharing system: programs of
higher priority are processed first, and program with the same
priority form a standard queue.
Application of Stack:
The Stack is Last In First Out (LIFO) data structure. This data structure has some
important applications in different aspect. These are like below −
Backtracking Procedure −
Backtracking is one of the algorithm designing technique. For that purpose,
we dive into some way, if that way is not efficient, we come back to the
previous state and go into some other paths. To get back from current state,
we need to store the previous state. For that purpose, we need stack. Some
examples of backtracking is finding the solution for Knight Tour problem or N-
Queen Problem etc.
Function Call Process:
Another great use of stack is during the function call
queue
All types of customer service(like railway reservation)
priority queues.
Dijkstra's shortest path algorithm implementation can
balancing and interrupt handling.
Priority queues are used in huffman codes for data
compression.
In traffic light, depending upon the traffic, the colors
over arrays
1) Dynamic size
2) Ease of insertion/deletion
backward.
Circular Linked List − Last item contains link of the first
element as next and the first element has a link to the last
element as previous.
Basic Operations:
Following are the basic operations supported by a list.
Insertion − Adds an element at the beginning of the list.
First, create a node using the same structure and find the
location where it has to be inserted
3. If ITEM=INFO[PTR], then:
3. If ITEM>INFO[PTR], then:
Set PTR:=LINK[PTR]
Else if ITEM=INFO[PTR], then:
set LOC:=PTR, and Exit [search is successful]
Else:
Set LOC:=NULL, and Exit
[End of If structure]
[End of step2 loop]
4. Set LOC:=NULL
5. Exit.
What do you mean by- (a) Memory Allocation (b)
Garbage Collection (c) Overflow & Underflow
a) Memory Allocation-
1.ptr->next = head;
Insertion after a given node: