0% found this document useful (0 votes)
103 views42 pages

Practical Assignment

The document provides code implementations for various data structures and algorithms problems in C language. It includes implementations of: 1. Binary search using recursion and iteration 2. Insertion sort 3. Quick sort 4. Merge sort 5. Reversing a string using a stack 6. Checking validity of expressions with nested parentheses 7. Converting infix to postfix notation 8. Evaluating a postfix expression 9. Basic queue operations using an array 10. Basic linked list operations For each problem, it provides the code implementation and sample output. The assignments aim to strengthen the students' understanding of algorithms and data structures.

Uploaded by

Ajit
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)
103 views42 pages

Practical Assignment

The document provides code implementations for various data structures and algorithms problems in C language. It includes implementations of: 1. Binary search using recursion and iteration 2. Insertion sort 3. Quick sort 4. Merge sort 5. Reversing a string using a stack 6. Checking validity of expressions with nested parentheses 7. Converting infix to postfix notation 8. Evaluating a postfix expression 9. Basic queue operations using an array 10. Basic linked list operations For each problem, it provides the code implementation and sample output. The assignments aim to strengthen the students' understanding of algorithms and data structures.

Uploaded by

Ajit
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

PRACTICAL ASSIGNMENT

M.Sc (CSA)-2ND, SEMESTER

Write a C program to:

1. Implement Binary Search (with and without recursion)

>>>> [with recursion]

CODE:
#include <stdio.h>
void binary_search(int [], int, int, int);
void bubble_sort(int [], int);
int main()
{
int key, size, i;
int list[25];
printf("Enter size of a list: ");
scanf("%d", &size);
printf("Enter elements\n");
for(i = 0; i < size; i++)
{
scanf("%d",&list[i]);
}
bubble_sort(list, size);
printf("\n");
printf("Enter key to search\n");
scanf("%d", &key);
binary_search(list, 0, size, key);
}
void bubble_sort(int list[], int size)
{
int temp, i, j;
for (i = 0; i < size; i++)
{
for (j = i; j < size; j++)
{
if (list[i] > list[j])
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}}}}
void binary_search(int list[], int lo, int hi, int key)
{
int mid;
if (lo > hi)
{
printf("Key not found\n");
return;
}
mid = (lo + hi) / 2;
if (list[mid] == key)
{
printf("Key found\n");
}
else if (list[mid] > key)
{
binary_search(list, lo, mid - 1, key);
}
else if (list[mid] < key)
{
binary_search(list, mid + 1, hi, key);
}
}

OUTPUT:--
[without recursion]

CODE;-

#include<stdio.h>
int main(){
int arr[50],i,n,x,flag=0,first,last,mid;
printf("Enter size of array:");
scanf("%d",&n);
printf("\nEnter array element(ascending order)\n");
for(i=0;i<n;++i)
scanf("%d",&arr[i]);
printf("\nEnter the element to search:");
scanf("%d",&x);
first=0;
last=n-1;
while(first<=last)
{
mid=(first+last)/2;
if(x==arr[mid]){
flag=1;
break;
}
else
if(x>arr[mid])
first=mid+1;
else
last=mid-1;
}
if(flag==1)
printf("\nElement found at position %d",mid+1);
else
printf("\nElement not found");
return 0;
}
OUTPUT

2. Implement Insertion Sort.


#include <stdio.h>
int main()
{
int n, array[1000], c, d, t;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 1 ; c <= n - 1; c++) {
d = c;
while ( d > 0 && array[d-1] > array[d]) {
t = array[d];
array[d] = array[d-1];
array[d-1] = t;
d--;
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c <= n - 1; c++) {
printf("%d\n", array[c]);
}
return 0;
}

OUTPUT

3. Implement Quick Sort.

CODE;

#include<stdio.h>
void quicksort(int number[25],int first,int last){
int i, j, pivot, temp;
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j){
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot])
j--;
if(i<j){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
}
int main(){
int i, count, number[25];
printf("How many elements are u going to enter?: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
quicksort(number,0,count-1);
printf("Order of Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0;
}

OUTPUT
4. Implement Merge Sort.
CODE:
#include <stdio.h>
#define max 10
int a[11] = { 40, 55, 80, 26,90, 25, 89, 78, 95, 10, 66 };
int b[10];
void merging(int low, int mid, int high) {
int l1, l2, i;
for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) {
if(a[l1] <= a[l2])
b[i] = a[l1++];
else
b[i] = a[l2++];
}
while(l1 <= mid)
b[i++] = a[l1++];
while(l2 <= high)
b[i++] = a[l2++];
for(i = low; i <= high; i++)
a[i] = b[i];
}
void sort(int low, int high) {
int mid;
if(low < high) {
mid = (low + high) / 2;
sort(low, mid);
sort(mid+1, high);
merging(low, mid, high);
} else {
return;
}
}
int main() {
int i;
printf("List before sorting\n");
for(i = 0; i <= max; i++)
printf("%d ", a[i]);
sort(0, max);
printf("\nList after sorting\n");
for(i = 0; i <= max; i++)
printf("%d ", a[i]);
}
OUTPUT:

5.Reverse a String using Stack.

CODE:

#include <stdio.h>
#include <string.h>
#define max 100
int top,stack[max];
void push(char x)
{
if(top == max-1){
printf("stack overflow");
} else {
stack[++top]=x;
}
}
void pop()
{
printf("%c",stack[top--]);
}
main()
{
printf("The given string is:\n");
printf("\tCRAB ) hgniS ramuK tijA(\n");
printf("After reversing, the string looks like:\n");
char str[]="CRAB )hgniS ramuK tijA";
int len = strlen(str);
int i;
for(i=0;i<len;i++)
push(str[i]);
for(i=0;i<len;i++)
pop();
}
OUTPUT;

6.Check the Validity of an expression containing nested parentheses.

CODE:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 20
struct stack
{
char stk[MAX];
int top;
}s;
void push(char item)
{
if (s.top == (MAX - 1))
printf ("Stack is Full\n");
else
{
s.top = s.top + 1;
s.stk[s.top] = item;
}
}
void pop()
{
if (s.top == - 1)
{
printf ("Stack is Empty\n");
}
else
{
s.top = s.top - 1;
}
}
int main()
{
char exp[MAX];
int i = 0;
s.top = -1;
printf("\nINPUT THE EXPRESSION : ");
scanf("%s", exp);
for(i = 0;i < strlen(exp);i++)
{
if(exp[i] == '(' || exp[i] == '[' || exp[i] == '{')
{
push(exp[i]);
continue;
}
else if(exp[i] == ')' || exp[i] == ']' || exp[i] == '}')
{
if(exp[i] == ')')
{
if(s.stk[s.top] == '(')
{
pop();
}
else
{
printf("\nUNBALANCED EXPRESSION\n");
break;
}
}
if(exp[i] == ']')
{
if(s.stk[s.top] == '[')
{
pop();
}
else
{
printf("\nUNBALANCED EXPRESSION\n");
break;
}
}
if(exp[i] == '}')
{
if(s.stk[s.top] == '{')
{
pop();
}
else
{
printf("\nUNBALANCED EXPRESSION\n");
break;
}
}
}
}
if(s.top == -1)
{
printf("\nBALANCED EXPRESSION\n");
}
}

OUTPUT:

7. Convert infix expression into postfix expression.

CODE:

#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:

8. Evaluate a postfix expression.

CODE:

#include<stdio.h>
#define MAX 20
typedef struct stack
{
int data[MAX];
int top;
}stack;
void init(stack *);
int empty(stack *);
int full(stack *);
int pop(stack *);
void push(stack *,int);
int evaluate(char x,int op1,int op2);
int main()
{
stack s;
char x;
int op1,op2,val;
init(&s);
printf("Enter the expression(eg: 59+3*)\nSingle digit operand and
operators only:");
while((x=getchar())!='\n')
{
if(isdigit(x))
push(&s,x-48);
else
{
op2=pop(&s);
op1=pop(&s);
val=evaluate(x,op1,op2);
push(&s,val);
}
}
val=pop(&s);
printf("\nValue of expression=%d",val);
return 0;
}
int evaluate(char x,int op1,int op2)
{
if(x=='+')
return(op1+op2);
if(x=='-')
return(op1-op2);
if(x=='*')
return(op1*op2);
if(x=='/')
return(op1/op2);
if(x=='%')
return(op1%op2);
}
void init(stack *s)
{
s->top=-1;
}
int empty(stack *s)
{
if(s->top==-1)
return(1);
return(0);
}
int full(stack *s)
{
if(s->top==MAX-1)
return(1);
return(0);
}
void push(stack *s,int x)
{
s->top=s->top+1;
s->data[s->top]=x;
}
int pop(stack *s)
{
int x;
x=s->data[s->top];
s->top=s->top-1;
return(x);
}

OUTPUT:
9. Implement all the basic operations of a queue using array.

CODE:

#include<stdio.h>
#define n 5
int main()
{
int queue[n],ch=1,front=0,rear=0,i,j=1,x=n;
printf("Queue using Array");
printf("\n1.Insertion \t2.Deletion \t3.Display \t4.Exit");
while(ch)
{
printf("\nEnter the Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
if(rear==x)
printf("\n Queue is Full");
else
{
printf("\n Enter no %d:",j++);
scanf("%d",&queue[rear++]);
}
break;
case 2:
if(front==rear)
{
printf("\n Queue is empty");
}
else
{
printf("\n Deleted Element is %d",queue[front++]);
x++;
}
break;
case 3:
printf("\nQueue Elements are:\n ");
if(front==rear)
printf("\n Queue is Empty");
else
{
for(i=front; i<rear; i++)
{
printf("%d\t",queue[i]);
}
break;
case 4:
exit(0);
default:
printf("Wrong Choice: please see the options");
}
}
}
return 0;
}

OUTPUT:

10. Implement all the basic operations of a Linked list.

CODE:
#include<stdio.h>
#include<stdlib.h>
int count=0;
struct Node *start=NULL;
struct Node
{
int data;
struct Node *next;
};
void insert_at_begin(int x)
{
struct Node *t;
t=(struct Node*)malloc(sizeof(struct Node));
count++;
if(start==NULL)
{
start=t;
start->data=x;
start->next=NULL;
return;
}
t->data=x;
t->next=start;
start=t;
}
void insert_at_end(int x)
{
struct Node *t,*temp;
t=(struct Node*)malloc(sizeof(struct Node));
count++;
if(start==NULL)
{
start=t;
start->data=x;
start->next=NULL;
return;
}
temp=start;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=t;
t->data=x;
t->next=NULL;
}
void delete_from_begin()
{
struct Node *t;
int n;
if(start==NULL)
{
printf("Linked List is empty!!!\n\n");
return;
}
n=start->data;
t=start->next;
free(start);
start=t;
count--;
printf("Deleted element is %d\n\n",n);
return;
}
void delete_from_end()
{
struct Node *t,*u;
int n;
if(start==NULL)
{
printf("Linked List is empty!!!\n\n");
return;
}
count--;
if(start->next==NULL)
{
n=start->data;
free(start);
start=NULL;
printf("Deleted element is %d\n\n",n);
return;
}
t=start;
while(t->next!=NULL)
{
u=t;
t=t->next;
}
n=t->data;
u->next=NULL;
free(t);
printf("Deleted element is %d\n\n",n);
return;
}
void display()
{
struct Node *t;
if(start==NULL)
{
printf("Linked List is empty!!!\n\n");
return;
}
printf("No of elements: %d\n",count);
printf("Elements are: ");
t=start;
while(t->next!=NULL)
{
printf("%d ",t->data);
t=t->next;
}
printf("%d ",t->data);
printf("\n\n");
}
int main()
{
int ch,data;
while(1)
{
printf("---LINKED LIST PROGRAMS---\n");
printf("1. INSERT AT BEGINING\n");
printf("2. INSERT AT END\n");
printf("3. DELETE FROM BEGINING\n");
printf("4. DELETE FROM END\n");
printf("5. DISPLAY LIST\n");
printf("6. EXIT\n\n");
printf("Enter your choice: ");
scanf("%d",&ch);
if(ch==1)
{
printf("Enter the insert value: ");
scanf("%d",&data);
printf("\n");
insert_at_begin(data);
}
else if(ch==2)
{
printf("Enter the insert value: ");
scanf("%d",&data);
printf("\n");
insert_at_end(data);
}
else if(ch==3)
{
delete_from_begin();
}
else if(ch==4)
{
delete_from_end();
}
else if(ch==5)
{
display();
}
else if(ch==6)
{
break;
}
else
{
printf("Wrong choice!!!\n");
}
}
}
OUTPUT;
11. Search an element in the Linked list of 10 nodes.

Code:

#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
} * head;
void createList(int n);
void displayList();
int search(int key);
int main()
{
int n, keyToSearch, index;
printf("Enter number of node to create: ");
scanf("%d", &n);
createList(n);
printf("\nData in list: \n");
displayList();
printf("\nEnter element to search: ");
scanf("%d", &keyToSearch);
index = search(keyToSearch);
if (index >= 0)
printf("%d found in the list at position %d\n",
keyToSearch, index + 1);
else
printf("%d not found in the list.\n", keyToSearch);
return 0;
}
void createList(int n)
{
struct node *newNode, *temp;
int data, i;
head = malloc(sizeof(struct node));
if (head == NULL)
{
printf("Unable to allocate memory. Exiting from
app.");
exit(0);
}
printf("Enter data of node 1: ");
scanf("%d", &data);
head->data = data;
head->next = NULL;
temp = head;
for (i = 2; i <= n; i++)
{
newNode = malloc(sizeof(struct node));
if (newNode == NULL)
{
printf("Unable to allocate memory. Exiting from
app.");
exit(0);
}
printf("Enter data of node %d: ", i);
scanf("%d", &data);
newNode->data = data;
newNode->next = NULL;
temp->next = newNode;
temp = temp->next;
}
}
void displayList()
{
struct node *temp;
if (head == NULL)
{
printf("List is empty.\n");
return;
}
temp = head;
while (temp != NULL)
{
printf("%d, ", temp->data);
temp = temp->next;
}
printf("\n");
}
int search(int key)
{
int index;
struct node *curNode;
index = 0;
curNode = head;
while (curNode != NULL && curNode->data != key)
{
index++;
curNode = curNode->next;
}
return (curNode != NULL) ? index : -1;
}

OUTPUT:
12. Implement queue using stack.

CODE:

#include <stdio.h>
#include <stdlib.h>
void push1(int);
void push2(int);
int pop1();
int pop2();
void enqueue();
void dequeue();
void display();
void create();
int st1[100], st2[100];
int top1 = -1, top2 = -1;
int count = 0;
void main()
{
int ch;
printf("\n1 - Enqueue element into queue");
printf("\n2 - Dequeu element from queue");
printf("\n3 - Display from queue");
printf("\n4 - Exit");
create();
while (1)
{
printf("\nEnter choice");
scanf("%d", &ch);
switch (ch)
{
case 1:
enqueue();
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("Wrong choice");
}
}
}
void create()
{
top1 = top2 = -1;
}
void push1(int data)
{
st1[++top1] = data;
}
int pop1()
{
return(st1[top1--]);
}
void push2(int data)
{
st2[++top2] = data;
}
int pop2()
{
return(st2[top2--]);
}
void enqueue()
{
int data, i;
printf("Enter data into queue");
scanf("%d", &data);
push1(data);
count++;
}
void dequeue()
{
int i;
for (i = 0;i <= count;i++)
{
push2(pop1());
}
pop2();
count--;
for (i = 0;i <= count;i++)
{
push1(pop2());
}
}
void display()
{
int i;
for (i = 0;i <= top1;i++)
{
printf(" %d ", st1[i]);
}
}

OUTPUT:
13. Implement Prim’s Algorithm.

CODE:

#include<stdio.h>
#include<stdlib.h>
#define infinity 9999
#define MAX 20
int G[MAX][MAX],spanning[MAX][MAX],n;
int prims();
int main()
{
int i,j,total_cost;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
total_cost=prims();
printf("\nspanning tree matrix:\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",spanning[i][j]);
}
printf("\n\nTotal cost of spanning
tree=%d",total_cost);
return 0;
}
int prims()
{
int cost[MAX][MAX];
int
u,v,min_distance,distance[MAX],from[MAX];
int visited[MAX],no_of_edges,i,min_cost,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(G[i][j]==0)
cost[i][j]=infinity;
else
cost[i][j]=G[i][j];
spanning[i][j]=0;
}
distance[0]=0;
visited[0]=1;
for(i=1;i<n;i++)
{
distance[i]=cost[0][i];
from[i]=0;
visited[i]=0;
}
min_cost=0;
no_of_edges=n-1;
while(no_of_edges>0)
{
min_distance=infinity;
for(i=1;i<n;i++)
if(visited[i]==0&&distance[i]<min_distanc
e)
{
v=i;
min_distance=distance[i];
}
u=from[v];
spanning[u][v]=distance[v];
spanning[v][u]=distance[v];
no_of_edges--;
visited[v]=1;
for(i=1;i<n;i++)
if(visited[i]==0&&cost[i][v]<distance[i])
{
distance[i]=cost[i][v];
from[i]=v;
}
min_cost=min_cost+cost[u][v];
}
return(min_cost);
}

OUTPUT;

14. Implement Kruskal Algorithm.


CODE:

#include<stdio.h>
#include<stdlib.h>
int i,j,k,a,b,u,v,n,ne=1;
int
min,mincost=0,cost[9][9],parent
[9];
int find(int);
int uni(int,int);
void main()
{
printf("\nImplementation of
Kruskal's algorithm\n");
printf("\nEnter the no. of
vertices:");
scanf("%d",&n);
printf("\nEnter the cost
adjacency matrix:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
}
printf("The edges of Minimum
Cost Spanning Tree are\n");
while(ne < n)
{
for(i=1,min=999;i<=n;i++)
{
for(j=1;j <= n;j++)
{
if(cost[i][j] < min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
u=find(u);
v=find(v);
if(uni(u,v))
{
printf("%d edge (%d,%d)
=%d\n",ne++,a,b,min);
mincost +=min;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n\tMinimum cost
= %d\n",mincost);
}
int find(int i)
{
while(parent[i])
i=parent[i];
return i;
}
int uni(int i,int j)
{
if(i!=j)
{
parent[j]=i;
return 1;
}
return 0;
}

OUTPUT:
15. Solve 0/1 knapsack problem.

CODE:
#include<stdio.h>
int max(int a, int b) { return (a > b)? a : b; }
int knapSack(int W, int wt[], int val[], int n)
{
int i, w;
int K[n+1][W+1];
for (i = 0; i <= n; i++)
{
for (w = 0; w <= W; w++)
{
if (i==0 || w==0)
K[i][w] = 0;
else if (wt[i-1] <= w)
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-
1][w]);
else
K[i][w] = K[i-1][w];
}
}
return K[n][W];
}
int main()
{
int i, n, val[20], wt[20], W;
printf("Enter number of items:");
scanf("%d", &n);
printf("Enter value and weight of items:\n");
for(i = 0;i < n; ++i){
scanf("%d%d", &val[i], &wt[i]);
}
printf("Enter size of knapsack:");
scanf("%d", &W);
printf("%d", knapSack(W, wt, val, n));
return 0;
}
OUTPUT:

You might also like