0% found this document useful (0 votes)
22 views29 pages

DS - Lab-Manual

Y4f yiggug fyi

Uploaded by

jay619001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views29 pages

DS - Lab-Manual

Y4f yiggug fyi

Uploaded by

jay619001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

SAL Institute of Technology & Engineering

Research

CE Department

Data Structures (3130702)

Laboratory Manual

Year: 2024-2025
INDEX

Sr. Page No.


No. Practical Date Marks Signature
From To
Introduction to pointers. Call by
1. Value and Call by reference.
Introduction to Dynamic Memory
2. Allocation. DMA functions
malloc(), calloc(), free(), etc.
Implement a program for stack that
3. performs following operations
using array. (a)PUSH (b) POP (c)
PEEP (d) CHANGE (e) DISPLAY.
Implement a program to convert
4. Infix notation to postfix notation
using stack.
Write a program to implement
5. QUEUE using arrays that performs
following operations (a) INSERT (b)
DELETE (c) DISPLAY.
Write a program to implement
6. Circular Queue using arrays that
performs following operations.
(a) INSERT (b) DELETE (c)
DISPLAY.
Write a menu driven program to
7. implement following operations on
the singly linked list
Implement recursive and non-
8. recursive tree traversing methods
inorder, preorder and post-order
traversal.
Write programs to implement
9. Sorting Algorithms.
Write a program to implement
10. Searching Algorithms.
Practical 1

Aim: Introduction to pointers. Call by Value and Call by reference.

Theory:

A pointer is nothing but a variable that contains an address of a location in memory. We can
declare the variable ptr as a pointer to an integer as

int *ptr;

You can think of this as being a new type, which is (int *), which means “pointer to an integer.”
When it is declared, a pointer does not have a value, which means that it does not yet store an
address in memory, and hence it does not point to an address in memory. Let’s say we want to
have the pointer that we defined point to the address of another integer.
This is done with

int x;
int *ptr;
ptr = &x;

The unary operatory & returns the address of a particular variable. We can represent the above
three lines of code graphically with

Since we did not assign the value of x, it does not contain a value. We can assign the value
of x in one of two ways. The first way is the most obvious way, which is simply x=5; The
pointer diagram now has a value at the location in which the variable is x is stored:

Pointers themselves also take up memory, since they store a number that is an address to
another location in memory. For the sake of argument, let’s say that the pointer ptr is located
at memory address 100 and that x is located at memory address 200, as depicted the following
diagram, which results when you declare
int x, *ptr;

When you set the pointer to point to the address of x with ptr=&x, you are assigning a
value of 200 to the pointer, so that the pointer diagram now looks like

3130702 DS
And when we set the value of x with either x=5 or *ptr=5, the pointer diagram looks like

Since the pointer simply stores the address of another variable, there is nothing to stop us from
setting the value of the integer x to the pointer ptr with

x=ptr;

In this case the pointer diagram would look like

But it is very rare that you would ever want to do this. Since pointers in general only store
addresses, it is much easier to understand pointers if we represent them in memory as blocks
with a dot at their center, with an arrow that points to the particular variable that exists at the
address of the pointer, as we did before, as in

since x is not a pointer but it still contains the address of ptr, then its value is 200.
Now consider the case when we declare more variables and pointers, such as

int x=10, y=5, *ptr1, *ptr2;


ptr1=&x;
ptr2=&y;

In this case the pointer diagram would look like

3130702 DS
For this simple case, you can think of dereferencing a pointer as only changing the values at
the addresses, while re-equating a pointer actually changes the pointers around. Consider the
dereferencing operations

*ptr1=y;
*ptr2=x;

This first one changes the value of x to y, while the second one changes the value of y to the
new value of x, which is the same as y, and hence does not change its value. The pointer
diagram after this operation looks like

These operations are identical to

x=y;
y=x;

Now consider the case in which we swap the pointers with

ptr1=&y;
ptr2=&x;

The pointer diagram now looks like

We can also set one pointer to the other,


ptr1=ptr2;
So now the pointers both point to the memory location of x, as in

3130702 DS
Passing Argument to Function:

In C Programming we have different ways of parameter passing schemes such as Call by


Value and Call by Reference. Function is good programming style in which we can write
reusable code that can be called whenever require. Whenever we call a function then sequence
of executable statements gets executed. We can pass some of the information to the function
for processing called argument.

Two Ways of Passing Argument to Function in C Language

1. Call by Reference
2. Call by Value
Call by Reference

1. While passing parameter using call by address scheme , we are passing the actual
address of the variable to the called function.
2. Any updates made inside the called function will modify the original copy since we are
directly modifying the content of the exact memory location.

Call by Value

1. While Passing Parameters using call by value , xerox copy of original parameter is
created and passed to the called function.
2. Any update made inside method will not affect the original value of variable in
calling function.
3. In the above example num1 and num2 are the original values and xerox copy of these
values is passed to the function and these values are copied into number1,number2
variable of sum function respectively.
4. As their scope is limited to only function so they cannot alter the values inside main
function.
Exercise:
1. Write a program to swap two variables using pointer and function. (Call by Valueand
Call by reference)
2. Write a program to add two variables using pointer and function. (Call by Valueand
Call by reference)

EVALUATION:

Problem Analysis Understanding Timely Mock Total


& Solution Level Completion
(3) (3) (2) (2) (10)

Signature with date: ______________

3130702 DS
Practical 2

Aim: Introduction to Dynamic Memory Allocation. DMA functions malloc(), calloc(),


free(), etc.

Theory:

Dynamic Memory Allocation


Dynamic allocation is the means by which a program can obtain memory while it is running.
Pointers provide necessary support for C’s powerful dynamic memory allocation. In general
global variables are allocated storage at compile time. Local variables use the program stack.
However neither global nor local variables can be added during program execution. Memory
allocated by C’s dynamic allocation functions come from the “heap”: the region of free
memory that lies between your program’s permanent storage area and the stack. In general
the heap contains a fairly large amount of free memory.
DMA functions

1. malloc( ) function
It dynamically allocates memory during the program. The function prototype is given below:
void * malloc(size_t , number_of_bytes);

After a successful call, malloc( ) returns a pointer to the first byte of the region of memory.
If memory is not enough the function returns a NULL.
Ex: Code fragments below allocate 1000 bytes of contiguous memory.
char *p;
p =(char *)malloc(1000); //(char *) forces void pointer to become a character
//pointer
Ex: Code below allocates space for 50 integers.
int *p;
p =(int *)malloc(50*sizeof(int)); //(int *) forces void pointer to become a integer
//pointer

2. free( ) function
It is the opposite of malloc( ). It returns previously allocated memory to the system. It has
the prototype below:
void free(void *p);

It is critical that you never call free( ) with an invalid argument. This will destroy the free
list.
3. calloc( ) function
calloc( ) function allocates an amount of memory equal to num*size. That is calloc( )
allocates enough memory for an array of num objects, each object being size bytes
long.Memory allocated by calloc( ) is released by free( ) function. The name calloc comes
from “contiguous allocation”. calloc( ) has the following function prototype.

void *calloc(size_t, n, size_t ,number_of_bytes);

3130702 DS
Ex: Code fragments below dynamically allocates 100 elements to an integer array.

int *p;
p = (int *) calloc(100,sizeof(int));//(int *) forces the void pointer to become a integer
//pointer
Exercise:

1. Write a C program to find sum of n elements entered by user. To perform this program,
allocate memory dynamically using malloc(),calloc() function.

EVALUATION:

Problem Analysis Understanding Timely Mock Total


& Solution Level Completion
(3) (3) (2) (2) (10)

Signature with date:

3130702 DS
Practical 3

Aim: Implement a program for stack that performs following operations using array.
(a)PUSH (b) POP (c) PEEP (d) CHANGE (e) DISPLAY

Theory:

A stack is a container of objects that are inserted and removed according to the last-in first-out
(LIFO) principle. In the pushdown stacks only two operations are allowed: push the item into the
stack, and pop the item out of the stack. A helpful analogy is to think of a stack of books; you can
remove only the top book, also you can add a new book on the top.

A stack is a recursive data structure. Here is a structural definition of a Stack:

A stack is either empty or it consists of a top and the rest which is a stack;

Primitive operations on stack are


1. Push (insert the element)
2. Pop (delete the element)
3. Peep
4. Change

ALGORITHMS:

1. Function : PUSH (S, TOP, X)


This procedure inserts an element x to the top of a stack which is represented by a vector S
containing N elements with a pointer TOP denoting the top element in the stack.

1. [Check for stack overflow]


If TOP ≥ N
Then write (‘STACK OVERFLOW’)
Return
2. [Increment TOP]
TOP ←TOP + 1
[Insert Element]
S[TOP] ←X
4. [Finished]
Return

2. Function : POP (S, TOP)

3130702 DS
This function removes the top element fom a stack which is represented by a vector S and
returns this element. TOP is a pointer to the top element of the stack.

1. [Check for underflow of stack]


If TOP = 0
Then Write (‘STACK UNDERFLOW ON POP’)
Take action in response to underflow
Return
2. [Decrement Pointer]
TOP ← TOP – 1
3. [Return former top element of stack]
Return (S[TOP + 1])

3. Function : PEEP (S, TOP, I)


Given a vector S (consisting of N elements) representing a sequentially allocated stack, and a
pointer TOP denoting the top element of the stack, this function returns the value of the ith
element from the TOP of the stack. The element is not deleted by this function.

1. [Check for stack Underflow]


If TOP - I +1 ≤ 0
Then Write (‘STACK UNDERFLOW ON PEEP’)
Take action in response to Underflow
Exit
2. [Return Ith element from top of the stack
Return (S[TOP – I + 1])

4. Function : CHANGE (S, TOP, X, I)


Given a vector S (consisting of N elements) representing a sequentially allocated stack, and a
pointer TOP denoting the top element of the stack. This procedure changes the value of the
Ith element from the top of the stack to the value containing in X.

1. [Check for stack Underflow]


If TOP – I + 1 ≤ 0
Then Write (‘STACK UNDERFLOW ON CHANGE’)
Return
2. [Change Ith element from top of the stack]
S[TOP – I + 1] ← X
3. [Finished]
Return

Exercise:

1. Write a C program to implement PUSH , POP, PEEP, CHANGE, DISPLAY


algorithm.

3130702 DS
EVALUATION:

Problem Analysis Understanding Timely Mock Total


& Solution Level Completion
(3) (3) (2) (2) (10)

Signature with date:

3130702 DS
Practical 4

Aim: Implement a program to convert Infix notation to postfix notation using stack.

Theory:

There is an algorithm to convert an infix expression into a postfix expression. It uses a stack;
but in this case, the stack is used to hold operators rather than numbers. The purpose of the
stack is to reverse the order of the operators in the expression. It also serves as a storage
structure, since no operator can be printed until both of its operands have appeared.

Example:

1. A * B + C becomes A B * C +

The order in which the operators appear is not reversed. When the '+' is read, it has lower
precedence than the '*', so the '*' must be printed first.

We will show this in a table with three columns. The first will show the symbol currently
being read. The second will show what is on the stack and the third will show the current
contents of the postfix string. The stack will be written from left to right with the 'bottom' of
the stack to the left.

current operator stack postfix string


symbol

1 A A

2 * * A

3 B * AB

4 + + A B * {pop and print the '*' before pushing the '+'}

5 C + AB*C
6 AB*C+

Infix to Postfix Conversion Algorithm

Let Q be any infix expression and we have to convert it to postfix expression P. For this the
following procedure will be followed.

1. Push left parenthesis onto STACK and add right parenthesis at the end of Q.

2. Scan Q from left to right and repeat step 3 to 6 for each element of Q until the STACK is
empty.

3130702 DS
3. If an operand is encountered add it to P.

4. If a left parenthesis is encountered push it onto the STACK.

5. If an operator is encountered, then

• Repeatedly pop from STACK and add to P each operator which has same
precedence as or higher precedence than the operator encountered.
• Push the encountered operator onto the STACK.

6. If a right parenthesis is encountered, then

• Repeatedly pop from the STACK and add to P each operator until a left
parenthesis is encountered.
• Remove the left parenthesis; do not add it to P.

7. Exit

Exercise:
1. Write a program to convert Infix notation to postfix notation using stack.

EVALUATION:

Problem Analysis Understanding Timely Mock Total


& Solution Level Completion
(3) (3) (2) (2) (10)

Signature with date:

3130702 DS
Practical 5

Aim: Write a program to implement QUEUE using arrays that performs following
operations (a) INSERT (b) DELETE (c) DISPLAY

Theory

Queue:
The queue can be formally defined as ordered collection of elements that has two ends named
as front and rear. From the front end one can delete the elements and from the rear end one
can insert the elements.

Queue principle: FIRST IN FIRST OUT = FIFO

It means: the first element inserted is the first one to be removed.

Primitive operations on Queue are

1. Insert (to add element into queue)


2. Delete (to delete element into queue)

ALGORITHMS:

1. Function: INSERT (Q, F, R, N, Y)

Given F and R, pointers to front and rear elements of a queue, a queue Q consisting of N
elements and an element Y, this function inserts Y at rear of the queue. Prior to first invocation
of procedure, F & R have been set to zero.

1. [Overflow]
If R>=N then Write(‘OVERFLOW’)
Return
2. [Increment rear pointer]
R=R+1
3. [Insert element]
Q[R] = Y
4. [Is front pointer properly set?]
If F=0 then F=1
Return

2. Function: REMOVE (Q, F, R)

Given F and R, the pointers to front and rear elements of a queue, respectively and the queue
Q to which they correspond, this function deletes and returns last element of queue. Y is a
temporary variable.

3130702 DS
1. [Underflow?]

If F=0 then Write (‘UNDERFLOW’)


Return (0)
2. [Delete element]
Y = Q[F]
3. [Queue empty?]
If F = R then F = R = 0
Else F = F+1
4. [Return element]
Return (Y)

Exercise:
1. Write a program to implement QUEUE using arrays that performs following
operations (a) INSERT (b) DELETE (c) DISPLAY

EVALUATION:

Problem Analysis Understanding Timely Mock Total


& Solution Level Completion
(3) (3) (2) (2) (10)

Signature with date:

3130702 DS
Practical 6

Aim: Write a program to implement Circular Queue using arrays that performs
following operations. (a) INSERT (b) DELETE (c) DISPLAY

Theory:

CIRCULAR QUEUE:
Circular queue is a linear data structure. It follows FIFO principle.
• In circular queue the last node is connected back to the first node to make a circle.
• Circular linked list fallow the First In First Out principle
• Elements are added at the rear end and the elements are deleted at front end of the
queue
• Both the front and the rear pointers points to the beginning of the array.
• It is also called as “Ring buffer”.

Primitive operations on Circular Queue are


1. INSERT ( )
2. DELETE ( )

1. Function: Insert-Circular-Q(CQueue, Rear, Front, N, Item)


Here, CQueue is a circular queue where to store data. Rear represents the location in which
the data element is to be inserted and Front represents the location from which the data
element is to be removed. Here N is the maximum size of CQueue and finally, Item is the
new item to be added. Initailly Rear = 0 and Front = 0.

1. If Front = 0 and Rear = 0 then Set Front := 1 and go to step 4.


2. If Front =1 and Rear = N or Front = Rear + 1
then Print: “Circular Queue Overflow” and Return.
3. If Rear = N then Set Rear := 1 and go to step 5.
4. Set Rear := Rear + 1
5. Set CQueue [Rear] := Item.
6. Return

2. Function: Delete-Circular-Q(CQueue, Front, Rear, Item)

Here, CQueue is the place where data are stored. Rear represents the location in which the
data element is to be inserted and Front represents the location from which the data element
is to be removed. Front element is assigned to Item. Initially, Front = 1.
1. If Front = 0 then
Print: “Circular Queue Underflow” and Return. /*..Delete without Insertion
2. Set Item :=CQueue [Front]
3. If Front = N then Set Front = 1 and Return.

3130702 DS
4. If Front = Rear then Set Front = 0 and Rear = 0 and Return.
5. Set Front := Front + 1
6. Return.

Exercise:
1. Write a program to implement Circular Queue using arrays that performs
following operations. (a) INSERT (b) DELETE (c) DISPLAY

EVALUATION:

Problem Analysis Understanding Timely Mock Total


& Solution Level Completion
(3) (3) (2) (2) (10)

Signature with date:

3130702 DS
Practical 7
Aim: Write a menu driven program to implement following operations on the singly
linked list.
(a) Insert a node at the front of the linked list.
(b) Insert a node at the end of the linked list.
(c) Insert a node such that linked list is in ascending order.(according to info.
Field)
(d) Delete a first node of the linked list.
(e) Delete a node before specified position.
(f) Delete a node after specified position.

Theory:

A linked list is a set of nodes where each node has two fields ‘data’ and a ‘link’. Where data
field stores the actual piece of information and ‘link’ field is used to point to next node.

Primitive operations on linked list are


1. Insert
2. Delete
3. Search
4. Display

ALGORITHMS:

1. INSERT (listptr, X)

Given X a new element and listptr, a pointer to first element of a linked list whose typical
node contains INFO and NEXT fields this function inserts X.

1. [Obtain a new free node]


p = new node
2. [Initialize fields of new node and its link to the list]
INFO (P) = X
NEXT (P) = listptr
3. [Make current node as first node in list]
listptr = p

2. DELETE (listptr, X)

This function is used to delete node X from list pointed by listptr.

1. [Empty list?]
If listptr = NULL then Write(‘LIST EMPTY’)
Return

3130702 DS
2. [Initialize search for X]
TEMP = listptr
3. [Find X]
Repeat thru step e while TEMP != X and NEXT (TEMP) != NULL
4. [Update predecessor marker]
PRED = TEMP
5. [Move to next node]
TEMP = NEXT (TEMP)
6. [End of the list?]
If TEMP != X then Write(‘NODE NOT FOUND’)
Return
7. [Delete X]
If X = listptr {Is X the first Node?}
then listptr = NEXT (listptr)
Else NEXT (PRED) = NEXT (X)
8. [Exit]
Return

3. SEARCH (X, listptr)

This function searches X in list pointed to by listptr.

1. [Empty list?]
If listptr = NULL then Write (‘LIST EMPTY’)
Return
2. [Initialize search for X]
TEMP = listptr
3. [Find X]
Repeat thru step 5 while TEMP != X and NEXT (TEMP) !=NULL
4. [Update predecessor marker]
PRED = TEMP
5. [Move to next node]
TEMP = NEXT (TEMP)
6. [End of the list?]
If TEMP != X then Write (‘NODE NOT FOUND’)
Return
7. [Display element & return]
Write (‘X’)
Return

3130702 DS
Exercise:
1. Write a menu driven program to implement following operations on the singly
linked list.
a) Insert a node at the front of the linked list.
b) Insert a node at the end of the linked list.
c) Insert a node such that linked list is in ascending order.(according to info.
Field)
d) Delete a first node of the linked list.
e) Delete a node before specified position.
f) Delete a node after specified position

EVALUAION:

Problem Analysis Understanding Timely Mock Total


& Solution Level Completion
(3) (3) (2) (2) (10)

Signature with date:

3130702 DS
Practical 8

Aim: Implement recursive and non-recursive tree traversing methods inorder,


preorder and post-order traversal.

Theory:

A binary tree is a finite set of nodes which is either empty or consists of a root and two
disjoint binary trees called the left sub-tree and right sub-tree.

Three different ways for traversing a binary tree are


1. In-order
2. Pre-order
3. Post-order

Algorithms:

1. Pre-order
void preorder(NODEPTR tree)
{
if(tree != NULL)
{
printf(“%d\n”, tree->info); //visit the root
pretrav(tree->left); //traverse left subtree
pretrav(tree->right); //traverse right subtree
}
}

2. In-order
void inorder(NODEPTR tree)
{
if(tree != NULL)
{
intrav(tree->left); //traverse left subtree
printf(“%d\n”, tree->info); //visit the root
intrav(tree->right); //traverse right subtree
}
}

3. Post-order

void postorder(NODEPTR tree)


{

if(tree != NULL)
{

3130702 DS
posttrav(tree->left); //traverse left subtree
posttrav(tree->right); //traverse right subtree
printf(“%d\n”, tree->info); //visit the root
}
}

Exercise:
1. Implement recursive and non-recursive tree traversing methods inorder, preorder and
post-order traversal.

EVALUAION:

Problem Analysis Understanding Timely Mock Total


& Solution Level Completion
(3) (3) (2) (2) (10)

Signature with date:

3130702 DS
Practical 9

Aim: Write programs to implement Sorting Algorithms.

Theory:

Sorting:
Sorting is systematic arrangement of the data. The systematic arrangement means based on
some key the data should be arranged.
Different Techniques of sorting
1. Bubble Sort
2. Merge Sort

ALGORITHMS:

1. Bubble Sort

Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison based
algorithm in which each pair of adjacent elements is compared and elements are swapped if
they are not in order. This algorithm is not suitable for large data sets as its average and worst
case complexity are of O(n2) where n are no. of items.

Algorithm: Bubble Sort

1. begin BubbleSort(list)
2. for all elements of list
3. if list[i] > list[i+1]
4. swap(list[i], list[i+1])
5. end if
6. end for
7. return list
8. end BubbleSort

2. Selection sort

Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2)
time complexity, making it inefficient on large lists, and generally performs worse than the
similar insertion sort. Selection sort is noted for its simplicity, and it has performance
advantages over more complicated algorithms in certain situations, particularly where
auxiliary memory is limited.

The algorithm divides the input list into two parts: the sublist of items already sorted, which
is built up from left to right at the front (left) of the list, and the sublist of items remaining to
be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted
sub list is the entire input list. The algorithm proceeds by finding the smallest (or largest,
depending on sorting order) element in the unsorted sublist, exchanging it with the leftmost

3130702 DS
unsorted element (putting it in sorted order), and moving the sublist boundaries one element
to the right.

Selection Sort (A)

1 for i <- 0 to n-1


2 small=i;
3 for j<-i+1 to n
4 if A[j] < A[small]
7 small=j;
8 temp = A[small];
9 A[small] = A[i];
10 A[i] = temp;

3. Insertion sort

Insertion sort iterates, consuming one input element each repetition, and growing a sorted
output list. Each iteration, insertion sort removes one element from the input data, finds the
location it belongs within the sorted list, and inserts it there. It repeats until no input elements
remain.

Insertion sort (A)

1 for j <- 2 to length[A]


2 do key <- A[j]
3 Insert A[j] into the sorted sequence A[1 . . j - 1].
4 i <- j - 1
5 while i > 0 and A[i] > key
6 do A[i + 1] <- A[i]
7 i <- i - 1
8 A[i + 1] <- key

4. Merge Sort

Merge sort is based on the divide-and-conquer paradigm. Its worst-case running time has a
lower order of growth than insertion sort. Since we are dealing with subproblems, we state
each subproblem as sorting a subarray A[p .. r]. Initially, p = 1 and r = n, but these values
change as we recurse through subproblems.

To sort A[p .. r]:

1. Divide Step

If a given array A has zero or one element, simply return; it is already sorted. Otherwise,
split A[p .. r] into two subarrays A[p .. q] and A[q + 1 .. r], each containing about half of
the elements of A[p .. r]. That is, q is the halfway point of A[p .. r].

2. Conquer Step

Conquer by recursively sorting the two subarrays A[p .. q] and A[q + 1 .. r].
3130702 DS
3. Combine Step

Combine the elements back in A[p .. r] by merging the two sorted subarrays A[p .. q]
and A[q + 1 .. r] into a sorted sequence. To accomplish this step, we will define a procedure
MERGE (A, p, q, r).

Algorithm: Merge Sort

To sort the entire sequence A[1 .. n], make the initial call to the procedure MERGE-
SORT (A, 1, n).

MERGE-SORT (A, p, r)

1. IF p < r // Check for base case


2. THEN q = FLOOR[(p + r)/2] // Divide step
3. MERGE (A, p, q) // Conquer step.
4. MERGE (A, q + 1, r) // Conquer step.
5. MERGE (A, p, q, r) // Conquer step.

The pseudocode of the MERGE procedure is as follow:

MERGE (A, p, q, r )

1. n1 ← q − p + 1
2. n2 ← r − q
3. Create arrays L[1 . . n1 + 1] and R[1 . . n2 + 1]
4. FOR i ← 1 TO n1
5. DO L[i] ← A[p + i − 1]
6. FOR j ← 1 TO n2
7. DO R[j] ← A[q + j ] 8.
L[n1 + 1] ← ∞
9. R[n2 + 1] ← ∞
10. i←1
11. j←1
12. FOR k ← p TO r
13. DO IF L[i ] ≤ R[ j]
14. THEN A[k] ← L[i]
15. i←i+1
16. ELSE A[k] ← R[j]
17. j←j+1

5. Quick Sort

Quick sort works by partitioning a given array A[p . . r] into two non-empty sub array A[p . .
q] and A[q+1 . . r] such that every key in A[p . . q] is less than or equal to every key in A[q+1
. . r]. Then the two subarrays are sorted by recursive calls to Quick sort. The exact position of
the partition depends on the given array and index q is computed as a part of the partitioning
procedure

3130702 DS
Algorithm: QuickSort(A, low, high)
{
If (low < high)
{
Pivot = Partition(A, low, high) //divide
QuickSort(A, low, pivot) //conquer
QuickSort (A, pivot, high) //conquer
}
}

As a first step, Quick Sort chooses as pivot one of the items in the array to be sorted. Then
array is then partitioned on either side of the pivot. Elements that are less than or equal to
pivot will move toward the left and elements that are greater than or equal to pivot will move
toward the right

Partitioning the Array


Partitioning procedure rearranges the sub-arrays in-place.

Algorithm: Partition(A, low, high)


pivot = A[low]
left = low
right = high
while (left < right)
{
while (A[left] < pivot)
left++;
while (A[right] > pivot)
right--;
if (left < right)
swap (A[left], A[right])
}
swap (A[right], pivot)
return right;

Partition selects the first key, A[pivot] as a pivot key about which the array will partitioned:
Keys ≤ A[pivot] will be moved towards the left .
Keys ≥ A[pivot] will be moved towards the right.

Exercise:
1. Write a program to implement Sorting Algorithm Bubble sort.
2. Write a program to implement Sorting Algorithm Selection sort.
3. Write a program to implement Sorting Algorithm Insertion sort.
4. Write a program to implement Sorting Algorithm Merge sort.
5. Write a program to implement Sorting Algorithm Quick sort.

3130702 DS
EVALUATION:

Problem Analysis Understanding Timely Mock Total


& Solution Level Completion
(3) (3) (2) (2) (10)

Signature with date:

3130702 DS
Practical 10

Aim: Write a program to implement Searching Algorithms.

Theory:

The necessary condition for this method is that all the elements should be sorted either in ascending
order or descending order. Once the data is sorted it is not necessary to compare each and every
record. The number of searches required in this method is reduced.

ALGORITHMS:

• BINARY_SEARCH (K,N,X)

Given an array K, consisting of N elements in ascending order, this algorithm searches


structure for a given element whose value is given by X. The variables LOW, MIDDLE,
HIGH denote lower, middle and upper limits of search interval. This function returns index
of vector element if search is successful and returns 0 otherwise.

1. [Initialize]
LOW = 1
HIGH = N
2. [Perform search]
Repeat thru step 4 while LOW <= HIGH
3. [Obtain index of midpoint of interval]
MIDDLE = [(LOW+HIGH)/2]
4. [COMPARE]
If X < K[MIDDLE] then HIGH = MIDDLE –1
Else
IF X> K[MIDDLE]
Then LOW = MIDDLE + 1
Else Write (‘SUCCESSFUL SEARCH’)
Return (MIDDLE)
5. [Unsuccessful Search]
Write (‘UNSUCCESSFUL SEARCH’)
Return (0)
Exercise:
1. Write a program to implement Linear search and Binary Search.
EVALUATION:
Problem Analysis Understanding Timely Mock Total
& Solution Level Completion
(3) (3) (2) (2) (10)

Signature with date:

3130702 DS
3130702 DS

You might also like