S.
NO: IMPLEMENTION RECURSIVE BINARY SEARCH
DATE:
AIM:
To write a C Program to implement searching techniques – Binary search.
ALGORITHMS:
Step 1: Sort the array in ascending order.
Step 2: Set the low index to the first element of the array and the high index to the last
element.
Step 3: Set the middle index to the average of the low and high indices.
Step 4: If the element at the middle index is the target element, return the middle index.
Step 5: If the target element is less than the element at the middle index, set the high index to
the middle index – 1.
Step 6: If the target element is greater than the element at the middle index, set the low index
to the middle index + 1.
Step 7: Repeat steps 3-6 until the element is found or it is clear that the element is not present
in the array.
PROGRAM:
#include <stdio.h>
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
return binarySearch(arr, mid + 1, r, x);
}
return -1;
}
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
if (result == -1)
printf("Element is not present in array");
else
printf("Element is present at index %d", result);
return 0;
}
OUTPUT:
Element is present at index 3
RESULT:
Thus the C Program to implement different searching techniques – Linear and Binary search
on a sorted array of ‘N’ numbers has been written and executed successfully.
[Link]: 2 IMPLEMENTION RECURSIVE BINARY SEARCH
DATE:
AIM:
To write a C Program to implement searching techniques – Binary search.
ALGORITHMS:
Step 1: First, read the search element (Target element) in the array.
Step 2: Set an integer i = 0 and repeat steps 3 to 4 till i reaches the end of the array.
Step 3: Match the key with arr[i].
Step 4: If the key matches, return the index. Otherwise, increment i by 1.
PROGRAMS:
#include <stdio.h>
int search(int arr[], int N, int x)
{
int i;
for (i = 0; i < N; i++)
if (arr[i] == x)
return i;
return -1;
}
// Driver code
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
int result = search(arr, N, x);
(result == -1)
? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}
OUTPUT:
Element is present at index 3
RESULT:
Thus the C Program to implement different searching techniques – Linear and Binary search
on a sorted array of ‘N’ numbers has been written and executed successfully
Ex No:3 Naive Pattern Searching algorithm
Date:
AIM:
To write a C Program to implement searching techniques – Naive Pattern
Searching algorithm
Algorithm:
i) It is the simplest method which uses brute force approach.
ii) It is a straight forward approach of solving the problem.
iii) It compares first character of pattern with searchable text. If match is found, pointers in
both strings are advanced. If match not found, pointer of text is incremented and pointer
ofpattern is reset. This process is repeated until the end of the text.
iv) It does not require any pre-processing. It directly starts comparing both strings character
by character.
PROGRAM:
#include <stdio.h>
#include <string.h>
void search(char* pat, char* txt)
{
int M = strlen(pat);
int N = strlen(txt);
/* A loop to slide pat[] one by one */
for (int i = 0; i <= N - M; i++) {
int j;
/* For current index i, check for pattern match */
for (j = 0; j < M; j++)
if (txt[i + j] != pat[j])
break;
if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1]
printf("Pattern found at index %d \n", i);
}
}
/* Driver program to test above function */
int main()
{
char txt[] = "AABAACAADAABAAABAA";
char pat[] = "AABA";
search(pat, txt);
return 0;
}
Output
Pattern found at index 0
Pattern found at index 9
Pattern found at index 13
RESULT:
Thus the C Program to implement different searching techniques – Linear and Binary search
on a sorted array of ‘N’ numbers has been written and executed successfully
Ex No:4(a) Insertion Sort Algorithm
Date:
Insertion Sort Algorithm
To sort an array of size N in ascending order:
Iterate from arr[1] to arr[N] over the array.
Compare the current element (key) to its predecessor.
If the key element is smaller than its predecessor, compare it to the elements before. Move
the greater elements one position up to make space for the swapped element.
Algorithm
The simple steps of achieving the insertion sort are listed as follows -
Step 1 - If the element is the first element, assume that it is already sorted. Return 1.
Step2 - Pick the next element, and store it separately in a key.
Step3 - Now, compare the key with all elements in the sorted array.
Step 4 - If the element in the sorted array is smaller than the current element, then move to
the next element. Else, shift greater elements in the array towards the right.
Step 5 - Insert the value.
Step 6 - Repeat until the array is sorted.
#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 from 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 8 32 17
after sorting array elements are
8 12 17 25 31 32
Ex No:4(b) Implementation of Heapsort
Date:
Implementation of Heapsort
Now, let's see the programs of Heap sort in different programming languages.
Program: Write a program to implement heap sort in C language.
#include <stdio.h>
int main()
{
int arr[10], no, i, j, c, heap_root, temp;
printf("Input number of elements: ");
scanf("%d", &no);
printf("\nInput array values one by one : ");
for (i = 0; i < no; i++)
scanf("%d", &arr[i]);
for (i = 1; i < no; i++)
{
c = i;
do
{
heap_root = (c - 1) / 2;
/* to create MAX arr array */
if (arr[heap_root] < arr[c])
{
temp = arr[heap_root];
arr[heap_root] = arr[c];
arr[c] = temp;
}
c = heap_root;
} while (c != 0);
}
printf("Heap array : ");
for (i = 0; i < no; i++)
printf("%d\t ", arr[i]);
for (j = no - 1; j >= 0; j--)
{
temp = arr[0];
arr[0] = arr[j];
arr[j] = temp;
heap_root = 0;
do
{
c = 2 * heap_root + 1;
if ((arr[c] < arr[c + 1]) && c < j-1)
c++;
if (arr[heap_root]<arr[c] && c<j)
{
temp = arr[heap_root];
arr[heap_root] = arr[c];
arr[c] = temp;
}
heap_root = c;
} while (c < j);
}
printf("\nSorted array : ");
for (i = 0; i < no; i++)
printf("\t%d", arr[i]);
printf("\n");
}
Sample Output:
Input number of elements:
Input array values one by one : Heap array : 56 12 15
Sorted array : 12 15 56
Graph Algorithms
555555
Ex No:5 Graph Traversal- BFS and DFS
Date
EXERCISE-9
Graph Traversal- BFS and DFS
AIM:
To write a C program implement DFS and BFS graph traversal.
ALGORITHM:
DFS
Step 1. Define a Stack of size total number of vertices in the graph.
Step 2. Select any vertex as starting point for traversal. Visit that vertex and push it on to the
Stack.
Step 3. Visit any one of the adjacent vertex of the verex which is at top of the stack which is
not visitedand push it on to the stack.
Step 4. Repeat step 3 until there are no new vertex to be visit from the vertex on top of the
stack.
Step 5. When there is no new vertex to be visit then use back tracking and pop one vertex
from the stack.
Step 6. Repeat steps 3, 4 and 5 until stack becomes Empty.
Step 7. When stack becomes Empty, then produce final spanning tree by removing unused
edges from thegraph
BFS
Step 1. Define a Queue of size total number of vertices in the graph.
Step 2. Select any vertex as starting point for traversal. Visit that vertex and insert it into the
Queue.
Step 3. Visit all the adjacent vertices of the verex which is at front of the Queue which is not
visited and
insert them into the Queue.
Step 4. When there is no new vertex to be visit from the vertex at front of the Queue then
delete that vertex
from the Queue.
Step 5. Repeat step 3 and 4 until queue becomes empty.
Step 6. When queue becomes Empty, then produce final spanning tree by removing unused
edges from the graph
PROGRAM
#include<stdio.h>
intq[20],top=-1,front=-1,rear=-1,a[20][20],vis[20],stack[20];
int delete();
void add(int item);
void bfs(int s,int n);
void dfs(int s,int n);
void push(int item);
int pop();
void main()
{
int n,i,s,ch,j;
char c,dummy;
printf("ENTER THE NUMBER VERTICES ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("ENTER 1 IF %d HAS A NODE WITH %d ELSE 0 ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("THE ADJACENCY MATRIX IS\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf(" %d",a[i][j]);
}
printf("\n");
}
do
{
for(i=1;i<=n;i++)
vis[i]=0;
printf("\nMENU");
printf("\n1.B.F.S");
printf("\n2.D.F.S");
printf("\nENTER YOUR CHOICE"); scanf("%d",&ch);
printf("ENTER THE SOURCE VERTEX :"); scanf("%d",&s);
switch(ch)
{
case 1:bfs(s,n);
break;
case 2:
dfs(s,n);
break;
}
printf("DO U WANT TO CONTINUE(Y/N) ? "); scanf("%c",&dummy);
scanf("%c",&c);
}while((c=='y')||(c=='Y'));
}
//**************BFS(breadth-first search) code**************//
void bfs(int s,int n)
{
int p,i;
add(s);
vis[s]=1;
p=delete();
if(p!=0)
printf(" %d",p);
while(p!=0)
{
for(i=1;i<=n;i++)
if((a[p][i]!=0)&&(vis[i]==0))
{
add(i);
vis[i]=1;
}
p=delete();
if(p!=0)
printf(" %d ",p);
}
for(i=1;i<=n;i++)
if(vis[i]==0)
bfs(i,n);
}
void add(int item)
{
if(rear==19)
printf("QUEUE FULL");
else
{
if(rear==-1)
{
q[++rear]=item;
front++;
}
else
q[++rear]=item;
}
}
int delete()
{
int k;
if((front>rear)||(front==-1))
return(0);
else
{
k=q[front++];
return(k);
}
}
//***************DFS(depth-first search) code******************//
void dfs(int s,int n)
{
int i,k;
push(s);
vis[s]=1;
k=pop();
if(k!=0)
printf(" %d ",k);
while(k!=0)
{
for(i=1;i<=n;i++)
if((a[k][i]!=0)&&(vis[i]==0)) {push(i);
vis[i]=1;
}
k=pop();
if(k!=0)
printf(" %d ",k);
}
for(i=1;i<=n;i++)
if(vis[i]==0)
dfs(i,n);
}
void push(int item)
{
if(top==19)
printf("Stack overflow "); else
stack[++top]=item;
}
int pop()
{
int k;
if(top==-1)
return(0);
else
{
k=stack[top--];
return(k);
}
}
OUTPUT:
ENTER THE NUMBER VERTICES 2
ENTER 1 IF 1 HAS A NODE WITH 1 ELSE 0 1
ENTER 1 IF 1 HAS A NODE WITH 2 ELSE 0 2
ENTER 1 IF 2 HAS A NODE WITH 1 ELSE 0 3
ENTER 1 IF 2 HAS A NODE WITH 2 ELSE 0 4
THE ADJACENCY MATRIX IS
12
34
MENU
1.B.F.S
2.D.F.S
ENTER YOUR CHOICE1
ENTER THE SOURCE VERTEX :1
1 2 DO U WANT TO CONTINUE(Y/N) ? y
MENU
1.B.F.S
2.D.F.S
ENTER YOUR CHOICE2
ENTER THE SOURCE VERTEX :2
2 1 DO U WANT TO CONTINUE(Y/N) ?
RESULT:
Thus the C program implemented DFS and BFS graph traversal was created and output was
verified.
Ex No:7 shortest path for graph using Dijkstra’s algorithm.
Date:
AIM:
To write a C program to find the shortest path for graph using Dijkstra’s algorithm.
ALGORITHM:
Step1: Include the all file headers.
Step2: Enter the weight of the path between the X and Y nodes.
Step3:Enter the source node of the vertex.
Step4:Enter the target node of the vertex.
Step5:Search shortest path between the source node to target of the vertex .
Step6:Display the shortest path .
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<string.h>
#include<math.h>
#define IN 99
#define N 6
int dijkstra(int cost[][N], int source, int target);
int main()
{
int cost[N][N],i,j,w,ch,co;
int source, target,x,y;
printf("\t The Shortest Path Algorithm ( DIJKSTRA'S ALGORITHM in C \n\n");
for(i=1;i< N;i++)
for(j=1;j< N;j++)
cost[i][j] = IN;
for(x=1;x< N;x++)
{
for(y=x+1;y< N;y++)
{
printf("Enter the weight of the path between nodes %d and %d: ",x,y);
scanf("%d",&w);
cost [x][y] = cost[y][x] = w;
}
printf("\n");
}
printf("\nEnter the source:");
scanf("%d", &source);
printf("\nEnter the target");
scanf("%d", &target);
co = dijsktra(cost,source,target);
printf("\nThe Shortest Path: %d",co);
}
int dijsktra(int cost[][N],int source,int target)
{
int dist[N],prev[N],selected[N]={0},i,m,min,start,d,j;
char path[N];
for(i=1;i< N;i++)
{
dist[i] = IN;
prev[i] = -1;
}
start = source;
selected[start]=1;
dist[start] = 0;
while(selected[target] ==0)
{
min = IN;
m = 0;
for(i=1;i< N;i++)
{
d = dist[start] +cost[start][i];
if(d< dist[i]&&selected[i]==0)
{
dist[i] = d;
prev[i] = start;
}
if(min>dist[i] && selected[i]==0)
{
min = dist[i];
m = i;
}
}
start = m;
selected[start] = 1;
}
start = target;
j = 0;
while(start != -1)
{
path[j++] = start+65;
start = prev[start];
}
path[j]='\0';
strrev(path);
printf("%s", path);
return dist[target];
}
OUTPUT:
RESULT:
Thus the C program implemented DFS and BFS graph traversal was created and output was
verified.
AIM
Ex No:8 PRIM’S ALGORITHM
Date:
To write a C program for constructing a minimum cost spanning tree of a graph using Prim’s
algorithm.
ALGORITHM
1. Start the program
2. Create edge list of given graph, with their weights.
3. Draw all nodes to create skeleton for spanning tree.
4. Select an edge with lowest weight and add it to skeleton and delete edge from edge list.
5. Add other edges. While adding an edge take care that the one end of the edge should
always be in
the skeleton tree and its cost should be minimum.
6. Repeat step 5 until n-1 edges are added.
7. Return.
PROGRAM
#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;
//create cost[][] matrix,spanning[][]
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; }
//initialise visited[],distance[] and from[]
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; //cost of spanning tree
no_of_edges=n
-1; //no. of edges to be added
while(no_of_edges>0) {
//find the vertex at minimum distance from the tree
min_distance=infinity;
for(i=1;i<n;i++)
if(visited[i]==0&&distance[i]<min_distance) {
v=i;
min_distance=distance[i]; }
u=from[v];
//insert the edge in spanning tree
spanning[u][v]=distance[v];
spanning[v][u]=distance[v];
no_of_edges--;
visited[v]=1;
//updated the distance[] array
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
Enter no. of vertices:5
Enter the adjacency matrix:
00316
30503
15056
60500
03600
spanning tree matrix:
00310
00503
35000
10000
03000
Total cost of spanning tree=12
Result:
Thus, the C program for constructing a minimum cost spanning tree of a graph using Prim’s
algorithm has been
implemented and executed.
Ex No:9 Warshall's algorithm
Date:
1.#include<stdio.h>
2.#include<conio.h>
3.#include<math.h>
[Link] max(int, int);
[Link] warshal(int p[10][10], int n) {
6. int i, j, k;
7. for (k = 1; k <= n; k++)
8. for (i = 1; i <= n; i++)
9. for (j = 1; j <= n; j++)
10. p[i][j] = max(p[i][j], p[i][k] && p[k][j]);
11. }
12. int max(int a, int b) {
13. ;
14. if (a > b)
15. return (a);
16. else
17. return (b);
18. }
19. void main() {
20. int p[10][10] = { 0 }, n, e, u, v, i, j;
21. printf("\n Enter the number of vertices:");
22. scanf("%d", &n);
23. printf("\n Enter the number of edges:");
24. scanf("%d", &e);
25. for (i = 1; i <= e; i++) {
26. //printf("\n Enter the end vertices of edge %d:",
i);
27. scanf("%d%d", &u, &v);
28. p[u][v] = 1;
29. }
30. printf("\n Matrix of input data: \n");
31. for (i = 1; i <= n; i++) {
32. for (j = 1; j <= n; j++)
33. printf("%d\t", p[i][j]);
34. printf("\n");
35. }
36. warshal(p, n);
37. printf("\n Transitive closure: \n");
38. for (i = 1; i <= n; i++) {
39. for (j = 1; j <= n; j++)
40. printf("%d\t", p[i][j]);
41. printf("\n");
42. }
43. getch();
44. }
Output:
$ gcc WarshallTransitiveClosure.c
$ ./[Link]
Enter the number of vertices: 5
Enter the number of edges: 11
Enter the end vertices of edge 1: 1 1
Enter the end vertices of edge 2: 1 4
Enter the end vertices of edge 3: 3 2
Enter the end vertices of edge 4: 3 3
Enter the end vertices of edge 5: 3 4
Enter the end vertices of edge 6: 4 2
Enter the end vertices of edge 7: 4 4
Enter the end vertices of edge 8: 5 2
Enter the end vertices of edge 9: 5 3
Enter the end vertices of edge 10: 5 4
Enter the end vertices of edge 11: 5 5
Matrix of input data:
1 0 0 1 0
0 0 0 0 0
0 1 1 1 0
0 1 0 1 0
0 1 1 1 1
Transitive closure:
1 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 1 0 1 0
0 1 1 1 1
Floyd's Algorithm
Ex No:10 Floyd's Algorithm
Date:
1. #include<stdio.h>
2. #include<conio.h>
3. int min(int,int);
4. void floyds(int p[10][10],int n) {
5. int i,j,k;
6. for (k=1;k<=n;k++)
7. for (i=1;i<=n;i++)
8. for (j=1;j<=n;j++)
9. if(i==j)
10. p[i][j]=0; else
11. p[i][j]=min(p[i][j],p[i][k]+p[k][j]);
12. }
13. int min(int a,int b) {
14. if(a<b)
15. return(a); else
16. return(b);
17. }
18. void main() {
19. int p[10][10],w,n,e,u,v,i,j;
20. ;
21. clrscr();
22. printf("\n Enter the number of vertices:");
23. scanf("%d",&n);
24. printf("\n Enter the number of edges:\n");
25. scanf("%d",&e);
26. for (i=1;i<=n;i++) {
27. for (j=1;j<=n;j++)
28. p[i][j]=999;
29. }
30. for (i=1;i<=e;i++) {
31. printf("\n Enter the end vertices of edge%d with its
weight \n",i);
32. scanf("%d%d%d",&u,&v,&w);
33. p[u][v]=w;
34. }
35. printf("\n Matrix of input data:\n");
36. for (i=1;i<=n;i++) {
37. for (j=1;j<=n;j++)
38. printf("%d \t",p[i][j]);
39. printf("\n");
40. }
41. floyds(p,n);
42. printf("\n Transitive closure:\n");
43. for (i=1;i<=n;i++) {
44. for (j=1;j<=n;j++)
45. printf("%d \t",p[i][j]);
46. printf("\n");
47. }
48. printf("\n The shortest paths are:\n");
49. for (i=1;i<=n;i++)
50. for (j=1;j<=n;j++) {
51. if(i!=j)
52. printf("\n <%d,%d>=%d",i,j,p[i][j]);
53. }
54. getch();
55. }
Output
Ex No:11 Finding Maximum and Minimum number using Divide and
Conquer Techniques
Date:
#include<stdio.h>
#include<stdio.h>
int max, min;
int a[100];
void maxmin(int i, int j)
{
int max1, min1, mid;
if(i==j)
{
max = min = a[i];
}
else
{
if(i == j-1)
{
if(a[i] <a[j])
{
max = a[j];
min = a[i];
}
else
{
max = a[i];
min = a[j];
}
}
else
{
mid = (i+j)/2;
maxmin(i, mid);
max1 = max; min1 = min;
maxmin(mid+1, j);
if(max <max1)
max = max1;
if(min > min1)
min = min1;
}
}
}
int main ()
{
int i, num;
printf ("\nEnter the total number of numbers : ");
scanf ("%d",&num);
printf ("Enter the numbers : \n");
for (i=1;i<=num;i++)
scanf ("%d",&a[i]);
max = a[0];
min = a[0];
maxmin(1, num);
printf ("Minimum element in an array : %d\n", min);
printf ("Maximum element in an array : %d\n", max);
return 0;
}
Output:
Enter the total number of numbers : Enter the numbers :
5
72
73
72
82
72
Minimum element in an array : 72
Maximum element in an array : 82
QUICK SORT
Ex QUICK SORT
No:12(a)
AIM:
To write a C program to implement the concept of Quick sort.
ALGORITHM:
Step 1: Start.
Step 2: Choose any element of the array to be the pivot.
Step 3: Divide all other elements (except the pivot) into two partitions.
i. All elements less than the pivot must be in the first partition.
ii. All elements greater than the pivot must be in the second partition.
Step 4: Use recursion to sort both partitions.
Step 5: Join the first sorted partition, the pivot, and the second sorted partition.
Step 6: Stop
PROGRAM:
#include<stdio.h>
#include<conio.h>
void qsort(int arr[20], int fst, int last);
void main(){
int arr[30];
int i,size;
printf("Enter total no. of the elements : ");
scanf("%d",&size);
printf("Enter total %d elements : \n",size);
for(i=0; i<size; i++)
scanf("%d",&arr[i]);
qsort(arr,0,size-1);
printf("Quick sorted elements are as : \n");
for(i=0; i<size; i++)
printf("%d\t",arr[i]);
getch();}
void qsort(int arr[20], int fst, int last){
int i,j,pivot,tmp;
if(fst<last){
pivot=fst;
i=fst;
j=last;
while(i<j){
while(arr[i]<=arr[pivot] && i<last)
i++;
while(arr[j]>arr[pivot])
j--;
if(i<j){
tmp=arr[i];
arr[i]=arr[j];
arr[j]=tmp;}}
tmp=arr[pivot];
arr[pivot]=arr[j];
arr[j]=tmp;
qsort(arr,fst,j-1);
qsort(arr,j+1,last);
}
}
OUTPUT:
Enter total no. of the elements : 5
Enter total 5 elements :
1
58
87
89
52
Quick sorted elements are as :
1 52 58 87 89
RESULT:
Thus the Quick sort C program has been written and executed successfully.
Ex Merge Sort
No:12(b)
Date:
Aim
To sort an array of N numbers using Merge sort.
Algorithm
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Divide the array into sub-arrays with a set of elements
5. Recursively sort the sub-arrays
6. Merge the sorted sub-arrays onto a single sorted array.
7. Stop
Program
/* Merge sort */
#include <stdio.h>
#include <conio.h>
void merge(int [],int ,int ,int );
void part(int [],int ,int );
int size;
main()
{
int i, arr[30];
printf("Enter total no. of elements : ");
scanf("%d", &size);
printf("Enter array elements : ");
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
part(arr, 0, size-1);
printf("\n Merge sorted list : ");
for(i=0; i<size; i++)
printf("%d ",arr[i]);
getch();
}
void part(int arr[], int min, int max)
{
int mid;
if(min < max)
{
mid = (min + max) / 2;
part(arr, min, mid);
part(arr, mid+1, max);
merge(arr, min, mid, max);
}
if (max-min == (size/2)-1)
{
printf("\n Half sorted list : ");
for(i=min; i<=max; i++)
printf("%d ", arr[i]);
}
}
void merge(int arr[],int min,int mid,int max)
{
int tmp[30];
int i, j, k, m;
j = min;
m = mid + 1;
for(i=min; j<=mid && m<=max; i++)
{
if(arr[j] <= arr[m])
{
tmp[i] = arr[j];
j++;
}
else
{
tmp[i] = arr[m];
m++;
}
}
if(j > mid)
{
for(k=m; k<=max; k++)
{
tmp[i] = arr[k];
i++;
}
}
else
{
for(k=j; k<=mid; k++)
{
tmp[i] = arr[k];
i++;
}
}
for(k=min; k<=max; k++)
arr[k] = tmp[k];
}
Output
Enter total no. of elements : 8
Enter array elements : 24 13 26 1 2 27 38 15
Half sorted list : 1 13 24 26
Half sorted list : 2 15 27 38
Merge sorted list : 1 2 13 15 24 26 27 38
Result
Thus array elements was sorted using merge sort's divide and conquer method.
Ex No:13 Implementation of N queen Problem using Backtracking
Date:
Algorithm for N queen problem:-
Initialize an empty chessboard of size NxN.
Start with the leftmost column and place a queen in the first row of that column.
Move to the next column and place a queen in the first row of that column.
Repeat step 3 until either all N queens have been placed or it is impossible to place a queen
in the current column without violating the rules of the problem.
If all N queens have been placed, print the solution.
If it is not possible to place a queen in the current column without violating the rules of the
problem, backtrack to the previous column.
Remove the queen from the previous column and move it down one row.
Repeat steps 4-7 until all possible configurations have been tried.
Program:
#include <stdio.h>
#include <conio.h>
//Number of queens
int N;
//chessboard
int board[100][100];
//function to check if the cell is attacked or not
int is_attack(int i,int j)
{
int k,l;
//checking if there is a queen in row or column
for(k=0;k<N;k++)
{
if((board[i][k] == 1) || (board[k][j] == 1))
return 1;
}
//checking for diagonals
for(k=0;k<N;k++)
{
for(l=0;l<N;l++)
{
if(((k+l) == (i+j)) || ((k-l) == (i-j)))
{
if(board[k][l] == 1)
return 1;
}
}
}
return 0;
}
int N_queen(int n)
{
int i,j;
//if n is 0, solution found
if(n==0)
return 1;
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
{
//checking if we can place a queen here or not
//queen will not be placed if the place is being attacked
//or already occupied
if((!is_attack(i,j)) && (board[i][j]!=1))
{
board[i][j] = 1;
//recursion
//wether we can put the next queen with this arrangment or not
if(N_queen(n-1)==1)
{
return 1;
}
board[i][j] = 0;
}
}
}
return 0;
}
void main()
{
int i,j;
clrscr();
//taking the value of N
printf("Enter the value of N for NxN chessboard\n");
scanf("%d",&N);
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
{
board[i][j]=0;
}
}
//calling the function
N_queen(N);
//printing the matix
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
printf("%d\t",board[i][j]);
printf("\n");
getch();
}
}
OUTPUT:
Enter the value of N for NxN chessboard
4
0 1 0 0
0 0 0 1
1 0 0 0
0 0 1 0
Ex No:14 Travelling Salesman Problem (TSP)
Date:
Travelling Salesman Problem (TSP) : Given a set of cities and distances between every pair
of cities, the problem is to find the shortest possible route that visits every city exactly once
and returns to the starting point.
#include<stdio.h>
int ary[10][10],completed[10],n,cost=0;
void takeInput()
{
int i,j;
printf("Enter the number of villages: ");
scanf("%d",&n);
printf("\nEnter the Cost Matrix\n");
for(i=0;i < n;i++)
{
printf("\nEnter Elements of Row: %d\n",i+1);
for( j=0;j < n;j++)
scanf("%d",&ary[i][j]);
completed[i]=0;
}
printf("\n\nThe cost list is:");
for( i=0;i < n;i++)
{
printf("\n");
for(j=0;j < n;j++)
printf("\t%d",ary[i][j]);
}
}
void mincost(int city)
{
int i,ncity;
completed[city]=1;
printf("%d--->",city+1);
ncity=least(city);
if(ncity==999)
{
ncity=0;
printf("%d",ncity+1);
cost+=ary[city][ncity];
return;
}
mincost(ncity);
}
int least(int c)
{
int i,nc=999;
int min=999,kmin;
for(i=0;i < n;i++)
{
if((ary[c][i]!=0)&&(completed[i]==0))
if(ary[c][i]+ary[i][c] < min)
{
min=ary[i][0]+ary[c][i];
kmin=ary[c][i];
nc=i;
}
}
if(min!=999)
cost+=kmin;
return nc;
}
void main()
{
takeInput();
printf("\n\nThe Path is:\n");
mincost(0);
printf("\n\nMinimum cost is %d\n ",cost);
getch();
}
OUT PUT:
Enter the number of villages: 3
Enter the Cost Matrix
Enter Elements of Row: 1
1
5
8
Enter Elements of Row: 2
4
9
8
Enter Elements of Row: 3
2
1
6
The cost list is:
1 5 8
4 9 8
2 1 6
The Path is:
1--->2--->3--->1
Minimum cost is 15
Ex No:14 Travelling Salesman Problem (TSP)
Date:
AIM:
ALGORITHM:
PROGRAM:
1.#include<stdio.h>
2.#include<math.h>
3.#include<time.h>
4.#include<stdlib.h>
5.
[Link] N = 20;
[Link] A[20];
8.
[Link] swap(int dex1, int dex2) {
10. int temp = A[dex1];
11. A[dex1] = A[dex2];
12. A[dex2] = temp;
13. }
14.
15. int partition(int start, int end) {
16. int i = start + 1;
17. int j = i;
18. int pivot = start;
19. for (; i < end; i++) {
20. if (A[i] < A[pivot]) {
21. swap(i, j);
22. j++;
23. }
24. }
25. if (j <= end)
26. swap(pivot, (j - 1));
27.
28. return j - 1;
29. }
30.
31. void quick_sort(int start, int end, int K) {
32. int part;
33. if (start < end) {
34. part = partition(start, end);
35. if (part == K - 1)
36. printf("kth smallest element : %d ", A[part]);
37. if (part > K - 1)
38. quick_sort(start, part, K);
39. else
40. quick_sort(part + 1, end, K);
41. }
42. return;
43. }
44.
45. int main(int argc, char **argv) {
46. int i;
47. time_t seconds;
48. time(&seconds);
49. srand((unsigned int) seconds);
50.
51. for (i = 0; i < N; i++)
52. A[i] = rand() % (1000 - 1 + 1) + 1;
53.
54. printf("The original sequence is: ");
55. for (i = 0; i < N; i++)
56. printf("%d ", A[i]);
57.
58. printf("\nEnter the Kth smallest you want to find: ");
59. int k;
60. scanf("%d", &k);
61. quick_sort(0, N, k);
62. }
Output:
$ gcc KthSmallestUsingPartitioning.c
$ ./[Link]
The original sequence is: 909 967 552 524 735 383 616 718 904 945 730 173
143 954 482 307 228 35 224 703
Enter the Kth smallest you want to find: 3
kth smallest element : 173