Alg Lab Manual
Alg Lab Manual
OUTPUT:
Enter the number of elements in array 5
Enter 5 numbers
10
20
5
18
7
Enter the number to search 18
18 is present at location 4.
RESULT:
Thus the program for linear search has been executed successfully.
EX.NO:2 BINARY SEARCH
AIM
To write a C program for binary search.
ALGORITHM
Step 1: Start a program
Step 2 - Read the search element from the user.
Step 3 - Find the middle element in the sorted list.
Step 4 - Compare the search element with the middle element in the sorted list.
Step 5 - If both are matched, then display "Given element is found!!!" and terminate the function.
Step 6 - If both are not matched, then check whether the search element is smaller or larger than the
middle element.
Step 7 - If the search element is smaller than middle element, repeat steps 3, 4 ,5 and 6 for the left
Sublist of the middle element.
Step 8 - If the search element is larger than middle element, repeat steps 3, 4,5 and 6 for the right
Sublist of the middle element.
Step 9 - Repeat the same process until we find the search element in the list or until sublist contains
only one element.
Step 10 - If that element also doesn't match with the search element, then display "Element is not found
in The list!!!" and terminate the function.
Step 11: Stop a program
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int first, last, middle, size, i, sElement, list[100];
clrscr();
printf("Enter the size of the list: ");
scanf("%d",&size);
printf("Enter %d integer values in Assending order\n", size);
for (i = 0; i < size; i++)
scanf("%d",&list[i]);
printf("Enter value to be search: ");
scanf("%d", &sElement);
first = 0;
last = size - 1;
middle = (first+last)/2;
while (first <= last)
{
if (list[middle] < sElement)
first = middle + 1;
else if (list[middle] == sElement)
{
printf("Element found at index %d.\n",middle);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Element Not found in the list.");
getch();
}
OUTPUT:
Enter the size of the list: 5
Enter 5 integer values in Assending order
10
20
25
32
47
Enter value to be search: 32
Element found at index 4.
RESULT:
Thus the program for binary search has been executed successfully.
EX.NO:3 PATTERN SEARCH USING NAIVE STRING MATCHING
ALGORITHM
AIM:
To write a C program to implement a pattern search using naive string matching algorithm.
ALGORITHM:
Step 1: Start a program.
Step 2: Declare a variable.
Step 3: 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 of
pattern is reset. This process is repeated until the end of the text.
Step 4: It does not require any pre-processing. It directly starts comparing both strings character by
character.
Step 5: Stop
PROGRAM
#include<stdio.h>
#include<conio.h>
#include<string.h>
int match(char st[100], char pat[100]);
int main(int argc, char **argv)
{
char st[100], pat[100];
int status;
printf("*** Naive String Matching Algorithm ***\n");
printf("Enter the String.\n");
gets(st);
printf("Enter the pattern to match.\n");
gets(pat);
status = match(st, pat);
if (status == -1)
printf("\nNo match found");
else
printf("Match has been found on %d position.", status);
return 0;
}
int match(char st[100], char pat[100])
{
int n, m, i, j, count = 0, temp = 0;
n = strlen(st);
m = strlen(pat);
for (i = 0; i <= n - m; i++)
{
temp++;
for (j = 0; j < m; j++)
{
if (st[i + j] == pat[j])
count++;
}
if (count == m)
return temp;
count = 0;
}
return -1;
}
OUTPUT:
*** Naive String Matching Algorithm ***
Enter the String.
raman likes mango
Enter the pattern to match.
mango
Match has been found on 13 position.
RESULT:
Thus the program to implement a pattern search using naive string matching algorithm has been
executed successfully.
EX.NO:4a INSERTION SORT
To write a C program for insertion sort.
ALGORITHM
Step 1: Start a program.
Step 2: If it is the first element, it is already sorted. return 1;
Step 3: Pick next element
Step 4: Compare with all elements in the sorted sub-list
Step 5: Shift all the elements in the sorted sub-list that is greater than the value to be sorted
Step 6: Insert the value
Step 7: Repeat until list is sorted
Step 8: Stop a program
PROGRAM:
#include<stdio.h>
#include<conio.h>
int main()
{
int data[100],n,temp,i,j;
clrscr();
printf("Enter number of terms(should be less than 100): ");
scanf("%d",&n);
printf("Enter elements: ");
for(i=0;i<n;i++)
{
scanf("%d",&data[i]);
}
for(i=1;i<n;i++)
{
temp = data[i];
j=i-1;
while(temp<data[j] && j>=0)
{
data[j+1] = data[j];
--j;
}
data[j+1]=temp;
}
printf("In ascending order: ");
for(i=0; i<n; i++)
printf("%d\t",data[i]);
return 0;
}
OUTPUT:
Enter number of terms(should be less than 100): 5
Enter elements:
50
25
10
75
12
In ascending order: 10 12 25 50 75
RESULT:
Thus the program for insertion sort has been executed successfully.
EX.NO:4b HEAP SORT
AIM:
To write a C program to implement a heap sort.
ALGORITHM:
Step 1: Start a program.
Step 2: Declare a variable.
Step 3: Build a binary heap.
Step 4: Start iterating from mid to the start of the binary heap array.
Step 5: On every iteration, swap the root node with the last leaf node.
Step 6: Remove the leaf node by putting it back at the end of the new sorted array.
Step 7: Again do the heapify operation and repeat the iteration from step 5.
Step 8: Stop
PROGRAM:
#include<stdio.h>
#include<conio.h>
void heapify(int*,int, int);
void heapsort(int*, int);
void print_array(int*, int);
int main()
{
int arr[] = { 10, 30, 5, 63, 22, 12, 56, 33 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("\nArray before sorting:\n");
print_array(arr, n);
heapsort(arr, n);
printf("\n\nArray after sorting:\n");
print_array(arr, n);
return 0;
}
void heapsort(int* arr, int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
{
heapify(arr, n, i);
}
for (int i = n - 1; i >= 0; i--)
{
int temp = arr[i];
arr[i] = arr[0];
arr[0] = temp;
heapify(arr, i, 0);
}
}
void heapify(int* arr, int n, int i)
{
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest])
{
largest = left;
}
if (right < n && arr[right] > arr[largest])
{
largest = right;
}
if (largest != i)
{
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
heapify(arr, n, largest);
}
}
void print_array(int* arr, int n)
{
for (int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
}
OUTPUT:
Array before sorting:
10 30 5 63 22 12 56 33
RESULT:
Thus the program to implement a heap sort has been executed successfully.
EX.NO:5 BREADTH FIRST SEARCH
AIM
To write a C program for breadth first search.
ALGORITHM
Step 1: Start the program
Step 2: Start by putting any one of the graph's vertices at the back of a queue.
Step 3: Take the front item of the queue and add it to the visited list.
Step 4: Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the
back of the queue
Step 5: Keep repeating steps 2 and 3 until the queue is empty.
Step 6: Stop the program
PROGRAM:
#include<stdio.h>
#include<conio.h>
int a[20][20], q[20], visited[20], n, i, j, f = 0, r = -1;
void bfs(int v)
{
for(i = 1; i <= n; i++)
if(a[v][i] && !visited[i])
q[++r] = i;
if(f <= r)
{
visited[q[f]] = 1;
bfs(q[f++]);
}
}
void main()
{
int v;
clrscr();
printf("\n Enter the number of vertices:");
scanf("%d", &n);
for(i=1; i <= n; i++)
{
q[i] = 0;
visited[i] = 0;
}
printf("\n Enter graph data in matrix form:\n");
for(i=1; i<=n; i++)
{
for(j=1;j<=n;j++)
{
scanf("%d", &a[i][j]);
}
}
printf("\n Enter the starting vertex:");
scanf("%d", &v);
bfs(v);
printf("\n The node which are reachable are:\n");
for(i=1; i <= n; i++)
{
if(visited[i])
printf("%d\t", i);
else
{
printf("\n Bfs is not possible. Not all nodes are reachable");
break;
}
}
getch();
}
OUTPUT:
Enter the number of vertices:4
Enter graph data in matrix form:
1111
0100
0010
0001
Enter the starting vertex:1
The nodes which are reachable are:
1 2 3 4
RESULT
Thus the C program for breadth first search has been executed successfully.
EX.NO:6 DEPTH FIRST SEARCH
AIM
To write a C program for depth first search.
ALGORITHM
Step 1: Start the program
Step 2: Start by putting any one of the graph's vertices on top of a stack.
Step 3: Take the top item of the stack and add it to the visited list.
Step 4: Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the
top of stack.
Step 5: Keep repeating steps 2 and 3 until the stack is empty.
Step 6: Stop the program
PROGRAM:
#include<stdio.h>
#include<conio.h>
void DFS(int);
int G[10][10],visited[10],n;
void main()
{
int i,j;
printf("Enter number of vertices:");
scanf("%d",&n);
printf("\nEnter adjecency matrix of the graph:");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
for(i=0;i<n;i++)
visited[i]=0;
DFS(0);
getch();
}
void DFS(int i)
{
int j;
printf("\n%d",i);
visited[i]=1;
for(j=0;j<n;j++)
if(!visited[j]&&G[i][j]==1)
DFS(j);
}
OUTPUT:
Enter number of vertices:4
Enter adjacency matrix of the graph:
1111
0100
0010
0001
0
1
2
3
RESULT
Thus the C program for depth first search has been executed successfully.
EX.NO:7 DIJKSTRA’S ALGORITHM
AIM:
To write a C program for dijkstra’s algorithm.
ALGORITHM:
Step 1: Start a program
Step 2: Create a set shortPath to store vertices that come in the way of the shortest path tree.
Step 3: Initialize all distance values as INFINITE and assign distance values as 0 for source vertex so
that it is picked first.
Step 4: Loop until all vertices of the graph are in the shortpath.
Step 5: Take a new vertex that is not visited and is nearest.
Step 6: Add this vertex to shortpath.
Step 7: For all adjacent vertices of this vertex update distances. Now check every adjacent vertex of V,
if sum of distance of u and weight of edge is elss the update it.
Step 8: Stop the program
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include <limits.h>
#define V 9
int minDistance(int dist[], bool sptSet[])
{
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false && dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
int printSolution(int dist[], int n)
{
printf("Vertex Distance from Source ");
for (int i = 0; i < V; i++)
printf("%d \t %d ", i, dist[i]);
}
void dijkstra(int graph[V][V], int src)
{
int dist[V];
bool sptSet[V];
for (int i = 0; i < V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
dist[src] = 0;
for (int count = 0; count < V - 1; count++)
{
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) dist[v] = dist[u]
+ graph[u][v];
}
printSolution(dist, V);
}
int main()
{
int graph[V][V] = { { 0, 6, 0, 0, 0, 0, 0, 8, 0 },
{ 6, 0, 8, 0, 0, 0, 0, 13, 0 },
{ 0, 8, 0, 7, 0, 6, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 6, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 13, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 }
};
dijkstra(graph, 0);
return 0;
}
OUTPUT:
Vertex Distance from Source
00
16
2 14
3 21
4 21
5 11
69
78
8 15
RESULT
Thus the C program for dijkstra’s algorithm has been executed successfully
EX.NO:8 PRIM’S ALGORITHM IMPLEMENTATION
AIM
To write a C program for finding shortest path using Prim’s algorithm.
ALGORITHM
Step 1: Start the program
Step 2: Create edge list of given graph, with their weights.
Step 3: Draw all nodes to create skeleton for spanning tree.
Step 4: Select an edge with lowest weight and add it to skeleton and delete edge from
edge list.
Step 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.
Step 6: Repeat step 5 until n-1 edges are added.
Step 7: Stop the program.
PROGRAM:
#include<stdio.h>
#include<conio.h>
struct tab
{
int v,pv,k,dv;
}a[10];
void main()
{
int b[10][10],i,j,m,f,c=0,n;
clrscr();
printf("Enter the number of vertices");
scanf("%d",&n);
printf("Input matrix");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&b[i][j]);
for(i=0;i<n;i++)
{
a[i].v=i+1;
a[i].pv=0;
a[i].dv=99;
a[i].k=0;
}
i=0;
a[i].dv=0;
for(;;)
{
a[i].k=1;
for(j=0;j<n;j++)
{
if(b[i][j]!=0&&b[i][j]!=99)
{
c=b[i][j];
if(c<a[j].dv)
{
a[j].pv = a[i].v;
a[j].dv = c;
}
}
}
f=1;
c=88;
for(m=0;m<n;m++)
{
if(a[m].k==0)
{
f=0;
if(a[m].dv<c &&a[m].dv!=0)
{
c=a[m].dv;
i=m;
}
}
}
if(f==1)
break;
}
printf("Vertex \tknown\t pv \tdv");
for(i=0;i<n;i++)
{
printf("\n %d\t%d \t%d\t%d",a[i].v,a[i].k,a[i].dv,a[i].pv);
}
getch();
}
OUTPUT:
Enter the number of vertices7
Input matrix
0241000
2 0 0 3 10 0 0
4002050
1320784
0 10 0 7 0 0 6
0058001
0004610
Vertex known pv dv
1100
2121
3124
4111
5167
6117
7116
RESULT:
Thus the program for prim’s algorithm has been executed successfully.
EX.NO:9 FLOYD’S ALGORITHM
AIM
To write a C program for finding all pairs shortest path using floyd’s algorithm.
ALGORITHM
Step 1: Start the program
Step 2: Declare the variable.
Step 3:Initialize the solution matrix same as the input graph matrix as a first step.
Step 4:Then update the solution matrix by considering all vertices as an intermediate vertex.
Step 5:The idea is to one by one pick all vertices and updates all shortest paths which include the
picked vertex as an intermediate vertex in the shortest path.
Step 6:When we pick vertex number k as an intermediate vertex, we already have considered
vertices {0, 1, 2, .. k-1} as intermediate vertices.
Step 7:For every pair (i, j) of the source and destination vertices respectively, there are two
possible cases.
-k is not an intermediate vertex in shortest path from i to j. We keep the value of dist[i][j]
as it is.
-k is an intermediate vertex in shortest path from i to j. We update the value of dist[i][j] as
dist[i][k] + dist[k][j] if dist[i][j] > dist[i][k] + dist[k][j].
Step 8: Stop the program.
PROGRAM:
#include<stdio.h>
#include<conio.h>
int main()
{
int wt[10][10],n,i,j;
void floyd(int matix[10][10],int n);
printf("\n create a graph using adjacency matrix");
printf("\n\nHow many vertices are there");
scanf("%d",&n);
printf("\n Enter the elements");
printf("Enter 999 as infinity");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("\nwt[%d][%d]",i,j);
scanf("%d",&wt[i][j]);
}
}
printf("\n\t Computing All pair shortest path..\n");
floyd(wt,n);
return 1;
}
void floyd(int wt[10][10],int n)
{
int d[5][10][10],i,j,k;
int min(int,int);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
d[0][i][j]=wt[i][j];
}
}
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
d[k][i][j]=min(d[k-1][i][j],(d[k-1][i][k]+d[k-1][k][j]));
}
}
}
for(k=0;k<=n;k++)
{
printf("R(%d)=\n",k);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%d",d[k][i][j]);
}
printf("\n");
}
}
}
int min(int a,int b)
{
if(a<b)
return a;
else
return b;
}
OUTPUT:
create a graph using adjacency matrix
RESULT:
Thus the program for finding all pairs shortest path using floyd’s algorithm has been executed
successfully.
EX.NO:10 WARSHALL’S ALGORITHM
AIM
To write a C program for computing transitive closure of a given directed graph using
warshall’s algorithm.
ALGORITHM
Step 1: Start the program
Step 2: Declare the variable.
Step 3:Initialize the solution matrix same as the input graph matrix as a first step.
Step 4:Then update the solution matrix by considering all vertices as an intermediate vertex.
Step 5:The idea is to one by one pick all vertices and updates all shortest paths which include the
picked vertex as an intermediate vertex in the shortest path.
Step 6:When we pick vertex number k as an intermediate vertex, we already have considered
vertices {0, 1, 2, .. k-1} as intermediate vertices.
Step 7: Stop the program.
PROGRAM
#include<stdio.h>
#include<conio.h>
int main()
{
int matrix[10][10],n,i,j;
void warshall(int matrix[10][10],int n);
printf("\n create a graph using adjacency matrix");
printf("\n\nHow many vertices are there");
scanf("%d",&n);
printf("\n Enter the elements");
//printf("Enter 999 as infinity");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("\nmatrix[%d][%d]",i,j);
scanf("%d",&matrix[i][j]);
}
}
printf("\n\t Computing transitive closure..\n");
warshall(matrix,n);
return 1;
}
void warshall(int matrix[10][10],int n)
{
int r[5][10][10],i,j,k;
int min(int,int);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
r[0][i][j]=matrix[i][j];
}
}
for(k=1;k<=n;k++)
{
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
r[k][i][j]=r[k-1][i][j]||r[k-1][i][k]&&r[k-1][k][j];
}
}
}
for(k=0;k<=n;k++)
{
printf("R(%d)=\n",k);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%d",r[k][i][j]);
}
printf("\n");
}
}
}
OUTPUT:
create a graph using adjacency matrix
RESULT:
Thus the program for computing transitive closure of a given directed graph using warshall’s
algorithm has been executed successfully.
EX.NO:11 FINDING MAXIMUM AND MINIMUM NUMBER IN A LIST
AIM
To write a C program for finding maximum and minimum number in a list.
ALGORITHM
Step 1: Start the program
Step 2: Declare the variable.
Step 3: Divide the original list at mid and get two sublists.
Step 4: Find min and max values respectively from each sublist until there is not
possible for division.
Step 5: Then combine the solution of min and max values respectively from each
sublist.
Step 6: Stop the program.
PROGRAM
#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:
RESULT:
Thus the program for finding maximum and minimum number in a list has been executed
successfully.
EX.NO:12a MERGE SORT
AIM:
To write a C program for merge sort.
ALGORITHM:
Step 1: Start a program
Step 2: Divide the unsorted array recursively until 1 element in each sub-array remains.
Step 3: Recursively, merge sub-arrays to produce sorted sub-arrays until all the sub-array merges and
only one array remains.
Step 4: To sort an array using Merge sort, following is the process
Step 4.1: We take two variables p & r where p stores the staring index & stores the last index of the
array Step 4.2: Next, we find the mid of the array to break it in two halves. Formula yo do so is (p+r)/2
and mark the middle element as m.
Step 4.3: Next step is to break the given array into two subarrays from the middle element, i.e. from
index p to m & m+1 to r.
Step 4.4: We continue to break the subarrays until we reach to a level where each sub array contains 1
element.
Step 4.5: Next we merge the sub-array recursively in a sorted order, so that we finally get a sorted
array. Step 5: Stop the program
PROGRAM:
#include<stdio.h>
#include<conio.h>
void mergesort(int a[],int i,int j);
void merge(int a[],int i1,int j1,int i2,int j2);
int main()
{
int a[30],n,i;
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
printf("\nSorted array is :");
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}
void mergesort(int a[],int i,int j)
{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid);
mergesort(a,mid+1,j);
merge(a,i,mid,mid+1,j);
}
}
void merge(int a[],int i1,int j1,int i2,int j2)
{
int temp[50];
int i,j,k;
i=i1;
j=i2;
k=0;
while(i<=j1 && j<=j2)
{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while(i<=j1)
temp[k++]=a[i++];
while(j<=j2)
temp[k++]=a[j++];
for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];
}
OUTPUT:
Enter no of elements: 8
Enter array elements:
50
25
10
75
12
5
7
55
Sorted array is: 5 7 10 12 25 50 55 75
RESULT
Thus the C program for merge sort has been executed successfully.
EX.NO: 12b QUICK SORT
AIM:
To write a C program for quick sort.
ALGORITHM:
Step 1: Start a program
Step 2: Pick an element from an array, call it as pivot element..
Step 3: Divide an unsorted array element into two arrays..
Step 4: If the value less than pivot element come under first sub array, the remaining elements with value
greater than pivot come in second sub array.
Step 4.1: T he pivot is in fixed position.
Step 4.2: All the left elements are less.
Step 4.3: The right elements are greater than pivot.
Step 4.4: Now, divide the array into 2 sub arrays left part and right part.
Step 5: Take left partition apply quick sort.
Step 6: All the left elements are less and sorted
Step 7:The right elements are greater and are in sorted order.
Step 8:The final sorted list is combining two sub arrays
Step 9: Stop the program
PROGRAM
#include<stdio.h>
#include<conio.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:
How many elements are u going to enter?: 8
Enter 8 elements: 5
3
1
9
8
2
4
7
Order of Sorted elements: 1 2 3 4 5 7 8 9
RESULT
Thus the C program for quick sort has been executed successfully.
EX.NO: 13 N QUEENS PROBLEM
AIM:
To write a C program for n queens problem.
ALGORITHM:
Step 1: Start a program
Step 2: Initialize an empty chessboard of size NxN.
Step 3: Start with the leftmost column and place a queen in the first row of that column
Step 4: Move to the next column and place a queen in the first row of that column.
Step 5: Repeat step 4 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
Step 6: If all N queens have been placed, print the solution.
Step 7: 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.
Step 8 Remove the queen from the previous column and move it down one row.
Step 9: Repeat steps 5-8 until all possible configurations have been tried.
Step 10: Stop the program
PROGRAM:
#include<stdio.h>
#include<math.h>
int board[20],count;
int main()
{
int n,i,j;
void queen(int row,int n);
printf(" - N Queens Problem Using Backtracking -");
printf("\n\nEnter number of Queens:");
scanf("%d",&n);
queen(1,n);
return 0;
}
void print(int n)
{
int i,j;
printf("\n\nSolution %d:\n\n",++count);
for(i=1;i<=n;++i)
printf("\t%d",i);
for(i=1;i<=n;++i)
{
printf("\n\n%d",i);
for(j=1;j<=n;++j) //for nxn board
{
if(board[i]==j)
printf("\tQ"); //queen at i,j position
else
printf("\t-"); //empty slot
}
}
}
int place(int row,int column)
{
int i;
for(i=1;i<=row-1;++i)
{
if(board[i]==column)
return 0;
else
if(abs(board[i]-column)==abs(i-row))
return 0;
}
return 1;
}
void queen(int row,int n)
{
int column;
for(column=1;column<=n;++column)
{
if(place(row,column))
{
board[row]=column; //no conflicts so place queen
if(row==n) //dead end
print(n); //printing the board configuration
else //try queen with next position
queen(row+1,n);
}
}
}
OUTPUT:
N Queens Problem Using Backtracking -
Enter number of Queens:4
Solution 1:
1 2 3 4
1 - Q - -
2 - - - Q
3 Q - - -
4 - - Q -
Solution 2:
1 2 3 4
1 - - Q -
2 Q - - -
3 - - - Q
4 - Q - -
RESULT
Thus the C program for n queens problem has been executed successfully.
EX.NO:14 FINDING KTH SMALLEST NUMBER USING RANDOMIZED ALGORITHM
AIM:
To write a C program for finding kth smallest number using randomized algorithm.
ALGORITHM:
Step 1: Start a program
Step 2: Apply quick sort algorithm on the input array.
Step 3: During quick sort select a pivot element randomly from the range of the array from low to high
and move it to its correct position.
Step 4: If index of pivot is equal to K then return the value..
Step 5: Else if the index of pivot is greater than K, then scan for the left subarray recursively ,else scan
for the right subarray recursively.
Step 6: Repeat this process until the element at index K is not found.
Step 7: Stop the program
PROGRAM
#include<stdio.h>
#include<math.h>
#include<time.h>
#include<stdlib.h>
int N = 20;
int A[20];
void swap(int dex1, int dex2) {
int temp = A[dex1];
A[dex1] = A[dex2];
A[dex2] = temp;
}
int partition(int start, int end) {
int i = start + 1;
int j = i;
int pivot = start;
for (; i < end; i++) {
if (A[i] < A[pivot]) {
swap(i, j);
j++;
}
}
if (j <= end)
swap(pivot, (j - 1));
return j - 1;
}
void quick_sort(int start, int end, int K) {
int part;
if (start < end) {
part = partition(start, end);
if (part == K - 1)
printf("kth smallest element : %d ", A[part]);
if (part > K - 1)
quick_sort(start, part, K);
else
quick_sort(part + 1, end, K);
}
return;
}
int main(int argc, char **argv)
{
int i;
time_t seconds;
time(&seconds);
srand((unsigned int) seconds);
for (i = 0; i < N; i++)
A[i] = rand() % (1000 - 1 + 1) + 1;
printf("The original sequence is: ");
for (i = 0; i < N; i++)
printf("%d ", A[i]);
printf("\nEnter the Kth smallest you want to find: ");
int k;
scanf("%d", &k);
quick_sort(0, N, k);
}
OUTPUT:
The original sequence is: 113 549 536 515 788 289 972 183 468 722 302 716 924 523 488 195 492 300
87 507
Enter the Kth smallest you want to find: 4
kth smallest element : 195
RESULT
Thus the C program for finding kth smallest number using randomized algorithm has been
executed successfully.