0% found this document useful (0 votes)
26 views25 pages

Data Structure Lab Manuuafinal

Uploaded by

ak99379762
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)
26 views25 pages

Data Structure Lab Manuuafinal

Uploaded by

ak99379762
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/ 25

DATA STRUCTURE LAB MANNUAL

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

NM Institute of Engineering & Technology


Patrapada, Bhubaneswar-751019
Approved by AICTE, New Delhi
Affiliated to BPUT, Odisha
TOPICS:-

Lab – 1

1. Write a C program to illustrate the Linear search in an array.

#include <stdio.h>
int main()
{
int array[100], search, c, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter a number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);
return 0;
}
output:
Enter the number of elements in array
5
Enter 5 numbers
5
6
4
2
9
Enter the number in search
4
4 is present in location 3
2.Write a C program to sort an array of integers using Bubble sort

#include <stdio.h>

// Swap function
void swap(int* arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

// A function to implement bubble sort


void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)

// Last i elements are already


// in place
for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(arr, j, j + 1);
}

// Function to print an array


void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver code
int main()
{
int arr[] = { 5, 1, 4, 2, 8 };
int N = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, N);
printf("Sorted array: ");
printArray(arr, N);
return 0;
}
Output

Sorted array: 1 2 4 5 8
3.Write a C program to illustrate the Binary search in an array.

#include <stdio.h>
int binarySearch(int array[], int x, int low, int high) {
while (low <= high) {
int mid = low + (high - low) / 2;
if (array[mid] == x)
return mid;
if (array[mid] < x)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main(void) {
int array[] = {3, 4, 5, 6, 7, 8, 9};
int n = sizeof(array) / sizeof(array[0]);
int x = 4;
int result = binarySearch(array, x, 0, n - 1);
if (result == -1)
printf("Not found");
else
printf("Element is found at index %d", result);
return 0;
}
Output:
Element is found at index 1
Lab -2
1.Write a C program to sort an array of integers using Selection sort.

#include <stdio.h>

void swap(int* xp, int* yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void selectionSort(int arr[], int n)


{
int i, j, min_idx;

// One by one move boundary of unsorted subarray


for (i = 0; i < n - 1; i++) {
// Find the minimum element in unsorted array
min_idx = i;
for (j = i + 1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first


// element
swap(&arr[min_idx], &arr[i]);
}
}

/* Function to print an array */


void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver program to test above functions


int main()
{
int arr[] = { 64, 25, 12, 22, 11 };
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
Output
Sorted array:
11 2 22 25 64

2.Write a C program to sort an array of integers using Insertion sort.

#include <stdio.h>

void insert(int a[], int n) /* function to sort an aay with insertion sort */
{
int i, j, temp;
for (i = 1; i < n; i++) {
temp = a[i];
j = i - 1;

while(j>=0 && temp <= a[j]) /* Move the elements greater than temp to one position ahead fro
m their current position*/
{
a[j+1] = a[j];
j = j-1;
}
a[j+1] = temp;
}
}

void printArr(int a[], int n) /* function to print the array */


{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}

int main()
{
int a[] = { 12, 31, 25, 8, 32, 17 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
insert(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);

return 0;
}
Output:

Before sorting array elements are


12 31 25 8 32 17
After sorting array elements are
8 12 17 25 31 32
2. Write a C program to sort an array of integers using Radix sort.
//radix sort program in c
#include <stdio.h>
// function to get maximum element from array
int find_max(int arr[], int n) {
int max_element = arr[0];
for(int i = 1; i<n; i++) {
if(arr[i] > max_element)
max_element = arr[i];
}
return max_element;
}
void countingSort(int arr[], int n, int pos)
{
int result[n + 1];
int count[10] = {0};
// count howmany numbers are present with digit 0-9 at given position
for (int i = 0; i < n; i++)
count[(arr[i] / pos) % 10]++;
// now do prefix sum of the count array
for (int i = 1; i < 10; i++)
count[i] += count[i - 1];
// Place the elements in sorted order
for (int i = n - 1; i >= 0; i--) {
result[count[(arr[i] / pos) % 10] - 1] = arr[i];
count[(arr[i] / pos) % 10]--;
}
for (int i = 0; i < n; i++)
arr[i] = result[i];
}
void radixsort(int arr[], int n) {
int max_element = find_max(arr, n);
// counting sort from the least significant digit to the most significant digit
for (int pos = 1; max_element / pos > 0; pos *= 10)
countingSort(arr, n, pos);
}
int main() {
int arr[] = {312, 42, 635, 11, 8, 783, 954, 777};
int n = sizeof(arr) / sizeof(arr[0]);
printf("An array before applying the radix sort: \n");
for (int i = 0; i < n; ++i) {
printf("%d ", arr[i]);
}
printf("\n");
radixsort(arr, n);
printf("An array after applying the radix sort: \n");
for (int i = 0; i < n; ++i) {
printf("%d ", arr[i]);
}
printf("\n");
}
Output
An array before applying the radix sort:
312 42 635 11 8 783 954 777
An array after applying the radix sort:
8 11 42 312 635 777 783 954

Lab-3

1. Write a menu driven C program to illustrate operations of Queue.


#include <stdio.h>

#define MAX 50

void insert();
void delete();
void display();
int queue_array[MAX];
int rear = - 1;
int front = - 1;
main()
{
int choice;
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice \n");
} /* End of switch */
} /* End of while */
} /* End of main() */

void insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
/*If queue is initially empty */
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
} /* End of insert() */

void delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
} /* End of delete() */

void display()
{
int i;
if (front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
}

OUTPUT:
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 10
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 15
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 20
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 30
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 2
Element deleted from queue is : 10
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 3
Queue is :
15 20 30
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 4
Lab-4

1.Write a C program to convert an infix expression into postfix expression


#include<stdio.h>
#include<ctype.h>

char stack[100];
int top = -1;

void push(char x)
{
stack[++top] = x;
}

char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}

int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}

int main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;

while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c ",pop());
push(*e);
}
e++;
}

while(top != -1)
{
printf("%c ",pop());
}return 0;
}
Output Test Case 1:
Enter the expression : a+b*c

abc*+
Output Test Case 2:
Enter the expression : (a+b)*c+(d-a)

ab+c*da-+
Output Test Case 3:
Enter the expression : ((4+8)(6-5))/((3-2)(2+2))
48+65-32-22+/
Lab-5
1.Write a C program to evaluate a postfix expression
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
// Stack implementation
int stack[MAX_SIZE];
int top = -1;
void push(int item) {
if (top >= MAX_SIZE - 1) {
printf("Stack Overflow\n");
return;
}
top++;
stack[top] = item;
}
int pop() {
if (top < 0) {
printf("Stack Underflow\n");
return -1;
}
int item = stack[top];
top--;
return item;
}
int is_operator(char symbol) {
if (symbol == '+' || symbol == '-' || symbol == '*' || symbol == '/') {
return 1;
}
return 0;
}
int evaluate(char* expression) {
int i = 0;
char symbol = expression[i];
int operand1, operand2, result;

while (symbol != '\0') {


if (symbol >= '0' && symbol <= '9') {
int num = symbol - '0';
push(num);
}
else if (is_operator(symbol)) {
operand2 = pop();
operand1 = pop();
switch(symbol) {
case '+': result = operand1 + operand2; break;
case '-': result = operand1 - operand2; break;
case '*': result = operand1 * operand2; break;
case '/': result = operand1 / operand2; break;
}
push(result);
}
i++;
symbol = expression[i];
}
result = pop();
return result;
}

int main() {
char expression[] = "5 6 7 + * 8 -";
int result = evaluate(expression);
printf("Result= %d\n", result);
return 0;
}
Output:

The output of the above program will be:


Result: 57

2. Write a C program to sort an integer array using Quick sort.

#include <stdio.h>

// Function to swap two elements


void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);

for (int j = low; j <= high - 1; j++) {


if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

// Function to print the array


void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

int main() {
int arr[] = { 12, 17, 6, 25, 1, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
Output
Sorted array:
1 5 6 12 17 25
Lab-6
1. Write a menu driven C program to illustrate different operations of single linked lists using
functions.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 30

struct emp_data
{
int empno;
char empName[MAX];
char designation[MAX];
struct emp_data *next;
};

/* Function to insert a node at the front of the linked list. */

struct emp_data *insert(struct emp_data *front, int id, char name[],


char desg[])
{
struct emp_data *newnode;

newnode = (struct emp_data*)malloc(sizeof(struct emp_data));

if (newnode == NULL)
{
printf("\n Allocation failed \n");
exit(2);
}
newnode->empno = id;
strcpy(newnode->empName, name);
strcpy(newnode->designation, desg);
newnode->next = front; fr
return(front);
}
/* End of insert() */

/* Function to display a node in a linked list */


void printNode(struct emp_data *p)
{
printf("\n Employee Details...\n");
printf("\n Emp No : %d", p->empno);
printf("\n Name : %s", p->empName);
printf("\n Designation : %s\n", p->designation);
printf("-------------------------------------\n");
}
/* End of printNode() */
/* Function to deleteNode a node based on employee number */
struct emp_data* deleteNode(struct emp_data *front, int id)
{
struct emp_data *ptr;
struct emp_data *bptr;

if (front->empno == id)
{
ptr = front;
printf("\n Node deleted:");
printNode(front); fr>next;
free(ptr);
return(front);
}
for (ptr = front->next, bptr = front; ptr != NULL; ptr = ptr->next,
bptr = bptr->next)
{
if (ptr->empno == id)
{
printf("\n Node deleted:");
printNode(ptr);
bptr->next = ptr->next;
free(ptr);
return(front);
}
}
printf("\n Employee Number %d not found ", id);
return(front);
}
/* End of deleteNode() */
/* Function to search the nodes in a linear fashion based emp ID */

void search(struct emp_data *front, int key)


{
struct emp_data *ptr;

for (ptr = front; ptr != NULL; ptr = ptr -> next)


{
if (ptr->empno == key)
{
printf("\n Key found:");
printNode(ptr);
return;
}
}
printf("\n Employee Number %d not found ", key);
}
/* End of search() */

/* Function to display the linked list */


void display(struct emp_data *front)
{
struct emp_data *ptr;
for (ptr = front; ptr != NULL; ptr = ptr->next)
{
printNode(ptr);
}
}
/* End of display() */

/* Function to display the menu of operations on a linked list */


void menu()
{
printf("---------------------------------------------\n");
printf("Press 1 to INSERT a node into the list \n");
printf("Press 2 to DELETE a node from the list \n");
printf("Press 3 to DISPLAY the list \n");
printf("Press 4 to SEARCH the list \n");
printf("Press 5 to EXIT \n");
printf("---------------------------------------------\n");
}
/* End of menu() */

/* Function to select the option */


char option()
{
char choice;

printf("\n\n>> Enter your choice: ");

switch(choice=getchar())
{
case '1':
case '2':
case '3':
case '4':
case '5': return(choice);
default : printf("\n Invalid choice.");
}
return choice;
}
/* End of option() */

/* The main() program begins */


void main()
{
struct emp_data *linkList;
char name[21], desig[51];
char choice;
int eno;

linkList = NULL;
printf("\n Welcome to demonstration of singly linked list \n");
menu();
do
{
/* choose oeration to be performed */
choice = option();
switch(choice)
{
case '1':
printf("\n Enter the Employee Number : ");
scanf("%d", & eno);
printf("Enter the Employee name : ");
scanf("%s", & name);
//gets(name);
printf("Enter the Employee Designation : ");
scanf("%s", & desig);
// gets(desig);
linkList = insert(linkList, eno, name, desig);
break;
case '2':
printf("\n\n Enter the employee number to be deleted: ");
scanf("%d", &eno;);
linkList = deleteNode(linkList, eno);
break;
case '3':
if (linkList == NULL)
{
printf("\n List empty.");
break;
}
display(linkList);
break;
case '4':
printf("\n\n Enter the employee number to be searched: ");
scanf("%d", &eno;);
search(linkList, eno);
break;
case '5': break;
}
} while (choice != '5');
}

OUTPUT

Welcome to a demonstration of a singly linked list


---------------------------------------------
Press 1 to INSERT a node into the list

Press 2 to DELETE a node from the list

Press 3 to DISPLAY the list


Press 4 to SEARCH the list

Press 5 to EXIT
---------------------------------------------

>> Enter your choice: 1


Enter the Employee Number: 1234
Enter the Employee name: Keerthi
Enter the Employee Designation: Engineer

>> Enter your choice: 1


Enter the Employee Number: 2345
Enter the Employee name: Srinivasan
Enter the Employee Designation: Specialist

>> Enter your choice: 1


Enter the Employee Number: 4567
Enter the Employee name: Annapurna
Enter the Employee Designation: Project Manager

>> Enter your choice: 3


Employee Details...
Emp No: 4567
Name: Annapoorna
Designation: Project Manager
-------------------------------------
Employee Details...
Emp No : 2345
Name : Srinivasan
Designation : Specilist
-------------------------------------
Employee Details...
Emp No: 1234
Name: Keerthi
Designation: Engineer
-------------------------------------

>> Enter your choice: 2


Enter the employee number to be deleted: 2345
Node deleted:
Employee Details...
Emp No: 2345
Name: Srinivasan
Designation: Specialist
-------------------------------------

>> Enter your choice: 3


Employee Details...
Emp No: 4567
Name: Annapurna
Designation: Project Manager
-------------------------------------
Employee Details...
Emp No: 1234
Name: Keerthi
Designation: Engineer

>> Enter your choice: 4


Enter the employee number to be searched: 2345
Employee Number 2345 not found
>> Enter your choice: 5

Lab-7
1. Write a C program to sort an integer array using Merge Sort

// C program for Merge Sort


#include <stdio.h>
#include <stdlib.h>

// Merges two subarrays of arr[].


// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

// Create temp arrays


int L[n1], R[n2];

// Copy data to temp arrays


// L[] and R[]
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];

// Merge the temp arrays back


// into arr[l..r]
// Initial index of first subarray
i = 0;

// Initial index of second subarray


j = 0;

// Initial index of merged subarray


k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}

// Copy the remaining elements


// of L[], if there are any
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

// Copy the remaining elements of


// R[], if there are any
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

// l is for left index and r is


// right index of the sub-array
// of arr to be sorted
void mergeSort(int arr[], int l, int r)
{
if (l < r) {
// Same as (l+r)/2, but avoids
// overflow for large l and h
int m = l + (r - l) / 2;

// Sort first and second halves


mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);

merge(arr, l, m, r);
}
}

// UTILITY FUNCTIONS
// Function to print an array
void printArray(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}

// Driver code
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);

printf("Given array is \n");


printArray(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);

printf("\nSorted array is \n");


printArray(arr, arr_size);
return 0;
}

Output
Given array is
12 11 13 5 6 7

Sorted array is
5 6 7 11 12 13

2. Write a C program to sort an integer array using Heap Sort.


#include <stdio.h>
/* function to heapify a subtree. Here 'i' is the
index of root node in array a[], and 'n' is the size of heap. */
void heapify(int a[], int n, int i)
{
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // left child
int right = 2 * i + 2; // right child
// If left child is larger than root
if (left < n && a[left] > a[largest])
largest = left;
// If right child is larger than root
if (right < n && a[right] > a[largest])
largest = right;
// If root is not largest
if (largest != i) {
// swap a[i] with a[largest]
int temp = a[i];
a[i] = a[largest];
a[largest] = temp;

heapify(a, n, largest);
}
}
/*Function to implement the heap sort*/
void heapSort(int a[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
heapify(a, n, i);
// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--) {
/* Move current root element to end*/
// swap a[0] with a[i]
int temp = a[0];
a[0] = a[i];
a[i] = temp;

heapify(a, i, 0);
}
}
/* function to print the array elements */
void printArr(int arr[], int n)
{
for (int i = 0; i < n; ++i)
{
printf("%d", arr[i]);
printf(" ");
}

}
int main()
{
int a[] = {48, 10, 23, 43, 28, 26, 1};
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
heapSort(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);
return 0;
}
Output
Before sorting elements are
48 10 23 43 28 26 1
After sorting array elements are
1 10 23 26 28 43 48

You might also like