DS - Lab-Manual
DS - Lab-Manual
Research
CE Department
Laboratory Manual
Year: 2024-2025
INDEX
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;
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
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
x=y;
y=x;
ptr1=&y;
ptr2=&x;
3130702 DS
Passing Argument to Function:
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:
3130702 DS
Practical 2
Theory:
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.
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:
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 either empty or it consists of a top and the rest which is a stack;
ALGORITHMS:
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.
Exercise:
3130702 DS
EVALUATION:
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.
1 A A
2 * * A
3 B * AB
5 C + AB*C
6 AB*C+
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.
• 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.
• 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:
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.
ALGORITHMS:
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
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?]
Exercise:
1. Write a program to implement QUEUE using arrays that performs following
operations (a) INSERT (b) DELETE (c) DISPLAY
EVALUATION:
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”.
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:
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.
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.
2. DELETE (listptr, X)
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
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:
3130702 DS
Practical 8
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.
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
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:
3130702 DS
Practical 9
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.
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.
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.
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.
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).
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)
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
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:
3130702 DS
Practical 10
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)
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)
3130702 DS
3130702 DS