Ex. No.
1 Implementation of Linear Search
Date:
Aim
To perform linear search of an element on the given array.
Algorithm
1. Start
2. Read number of array elements n
3. Read array elements Ai, i = 0,1,2,…n–1
4. Read search value
5. Assign 0 to found
6. Check each array element against search
If Ai = search then
found = 1
Print "Element found"
Print position i
Stop
7. If found = 0 then
print "Element not found"
8. Stop
Program
/* Linear search on a sorted array */
#include <stdio.h>
#include <conio.h>
main()
int a[50],i, n, val, found;
clrscr();
printf("Enter number of elements : "); scanf("%d", &n);
printf("Enter Array Elements : \n");
for(i=0; i<n;i++)
scanf("%d", &a[i]);
printf("Enter element to locate : ");
scanf("%d", &val);
found = 0;
for(i=0; i<n; i++)
if (a[i] == val)
printf("Element found at position %d", i);
found = 1;
break;
if (found == 0)
printf("\n Element not found");
getch();
Output
Enter number of elements : 7
Enter Array Elements :
23 6 12 5 0 32 10
Enter element to locate : 5
Element found at position 3
Result
Thus an array was linearly searched for an element's existence.
Ex. No. 2 Implementation of Recursive binary search
Date:
Aim
Algorithm:
Program:
#include <stdio.h>
int binarySearch(int arr[], int l, int r, int x)
if (r >= l)
int mid = l + (r - l)/2;
// If the element is present at the middle itself
if (arr[mid] == x) return mid;
// If element is smaller than mid, then it can only be present
// in left subarray
if (arr[mid] > x) return binarySearch(arr, l, mid-1, x);
// Else the element can only be present in right subarray
return binarySearch(arr, mid+1, r, x);
// We reach here when element is not present in array
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
Ex. No. 3 Implementation of Naïve algorithm for pattern Matching
Date:
Aim
Algorithm:
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's code
int main()
char txt[] = "AABAACAADAABAAABAA";
char pat[] = "AABA";
// Function call
search(pat, txt);
return 0;
Output
Pattern found at index 0
Pattern found at index 9
Pattern found at index 13
Result:
Ex. No.4 Implementation of Sorting- Insertion Sort
Date:
Aim
To sort an array of N numbers using Insertion sort.
Algorithm
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Sort the elements using insertion sort
In pass p, move the element in position p left until its correct place
is foundamong the first p + 1 elements.
Element at position p is saved in temp, and all larger
elements (prior to position p) are moved one spot to the
right. Then temp is placed in the correct spot.
5. Stop
Program:
main()
int i, j, k, n, temp, a[20], p=0;
printf("Enter total elements:
");scanf("%d",&n);
printf("Enter array elements:
");for(i=0; i<n; i++)
scanf("%d", &a[i]);
for(i=1; i<n; i++)
temp =
a[i];j = i -
1;
while((temp<a[j]) && (j>=0))
a[j+1] =
a[j];j = j - 1;
a[j+1] = temp;
p++;
printf("\n After Pass %d: ",
p);for(k=0; k<n; k++)
printf(" %d", a[k]);
}
printf("\n Sorted List :
");for(i=0; i<n; i++)
printf(" %d", a[i]);
Output
Enter total elements: 6
Enter array elements: 34 8 64 51 32 21
After Pass 1: 8 34 64 51 32 21
After Pass 2: 8 34 64 51 32 21
After Pass 3: 8 34 51 64 32 21
After Pass 4: 8 32 34 51 64 21
After Pass 5: 8 21 32 34 51 64
Sorted List : 8 21 32 34 51 64
Result
Thus array elements was sorted using insertion sort.
Ex. No.5 Implementation of Heap sort
Date:
Aim
Algorithm
Program:
#include <stdio.h>
// Function to swap the position of two elements
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
// To heapify a subtree rooted with node i
// which is an index in arr[].
// n is size of heap
void heapify(int arr[], int N, int i)
// Find largest among root, left child and right child
// Initialize largest as root
int largest = i;
// left = 2*i + 1
int left = 2 * i + 1;
// right = 2*i + 2
int right = 2 * i + 2;
// If left child is larger than root
if (left < N && arr[left] > arr[largest])
largest = left;
// If right child is larger than largest
// so far
if (right < N && arr[right] > arr[largest])
largest = right;
// Swap and continue heapifying if root is not largest
// If largest is not root
if (largest != i) {
swap(&arr[i], &arr[largest]);
// Recursively heapify the affected
// sub-tree
heapify(arr, N, largest);
// Main function to do heap sort
void heapSort(int arr[], int N)
{
// Build max heap
for (int i = N / 2 - 1; i >= 0; i--)
heapify(arr, N, i);
// Heap sort
for (int i = N - 1; i >= 0; i--) {
swap(&arr[0], &arr[i]);
// Heapify root element to get highest element at
// root again
heapify(arr, i, 0);
// A utility function to print array of size n
void printArray(int arr[], int N)
for (int i = 0; i < N; i++)
printf("%d ", arr[i]);
printf("\n");
// Driver's code
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
heapSort(arr, N);
printf("Sorted array is\n");
printArray(arr, N);
Output:
Sorted array is
5,6,7,11,12,14
Result:
Ex.No.6 Breadth First Search
Date :
Aim :
To perform Breadth First Search of given in the graph.
Algorithm :
Step 1: SET STATUS = 1 (ready state) for each node in G
Step 2: Enqueue the starting node A and set its STATUS = 2 (waiting state)
Step 3: Repeat Steps 4 and 5 until QUEUE is empty
Step 4: Dequeue a node N. Process it and set its STATUS = 3 (processed state).
Step 5: Enqueue all the neighbours of N that are in the ready state (whose STATUS = 1) and set
their STATUS = 2
(waiting state)
[END OF LOOP]
Step 6: EXIT
Program :
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 50
// This struct represents a directed graph using
// adjacency list representation
typedef struct Graph_t {
int V; // No. of vertices
bool adj[MAX_VERTICES][MAX_VERTICES];
} Graph;
// Constructor
Graph* Graph_create(int V)
Graph* g = malloc(sizeof(Graph));
g->V = V;
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
g->adj[i][j] = false;
return g;
// Destructor
void Graph_destroy(Graph* g) { free(g); }
// function to add an edge to graph
void Graph_addEdge(Graph* g, int v, int w)
g->adj[v][w] = true; // Add w to v’s list.
// prints BFS traversal from a given source s
void Graph_BFS(Graph* g, int s)
{
// Mark all the vertices as not visited
bool visited[MAX_VERTICES];
for (int i = 0; i < g->V; i++) {
visited[i] = false;
// Create a queue for BFS
int queue[MAX_VERTICES];
int front = 0, rear = 0;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue[rear++] = s;
while (front != rear) {
// Dequeue a vertex from queue and print it
s = queue[front++];
printf("%d ", s);
// Get all adjacent vertices of the dequeued
// vertex s. If a adjacent has not been visited,
// then mark it visited and enqueue it
for (int adjacent = 0; adjacent < g->V;
adjacent++) {
if (g->adj[s][adjacent] && !visited[adjacent]) {
visited[adjacent] = true;
queue[rear++] = adjacent;
// Driver program to test methods of graph struct
int main()
// Create a graph given in the above diagram
Graph* g = Graph_create(4);
Graph_addEdge(g, 0, 1);
Graph_addEdge(g, 0, 2);
Graph_addEdge(g, 1, 2);
Graph_addEdge(g, 2, 0);
Graph_addEdge(g, 2, 3);
Graph_addEdge(g, 3, 3);
printf("Following is Breadth First Traversal "
"(starting from vertex 2) \n");
Graph_BFS(g, 2);
Graph_destroy(g);
return 0;
}
Output
Following is Breadth First Traversal (starting from vertex 2)
2031
Result :
To perform Breadth First Search of given in the graph graph is verified successfully.
Ex. No.7 Implementation of Sorting- Merge Sort
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 i, 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])
else
tmp[i] = arr[j];
j++;
tmp[i] = arr[m];
m++;
if(j > mid)
for(k=m; k<=max; k++)
else
tmp[i] = arr[k];
i++;
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. 8 Implementation of Prim’s Algorithm
Date:
Aim
To implement the Prim’s Algorithm in C program.
Algorithm
Step 1: Select a starting vertex
Step 2: Repeat Steps 3 and 4 until there are fringe vertices
Step 3: Select an edge 'e' connecting the tree vertex and fringe vertex that has minimum weight
Step 4: Add the selected edge and the vertex to the minimum spanning tree T
[END OF LOOP]
Step 5: EXIT
Program
#include<stdio.h>
#include<conio.h>
int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
void main()
printf("\nEnter the number of nodes:");
scanf("%d",&n);
printf("\nEnter the 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; }
visited[1]=1;
printf("\n");
while(ne < n)
for(i=1,min=999;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]< min)
if(visited[i]!=0)
min=cost[i][j];
a=u=i;
b=v=j;
if(visited[u]==0 || visited[v]==0)
printf("\n Edge %d:(%d %d) cost:%d",ne++,a,b,min);
mincost+=min;
visited[b]=1;
cost[a][b]=cost[b][a]=999;
}
printf("\n Minimun cost=%d",mincost);
getch();
Output
Result
Thus the C program for the implementation of Prim’s algorithm is executed successfully
Ex. No. 9 Implementation of Dijkstra’s Algorithm
Date:
Aim
To find the shortest path for the given graph from a specified source to all other
vertices using Dijkstra’s algorithm.
Algorithm
1. Start
2. Obtain no. of vertices and adjacency matrix for the given graph
3. Create cost matrix from adjacency matrix. C[i][j] is the cost of going from
vertex i to vertex j. If there is no edge between vertices i and j then C[i][j] is
infinity
4. Initialize visited[] to zero
5. Read source vertex and mark it as visited
6. Create the distance matrix, by storing the cost of vertices from vertex no. 0 to n-1
from the source vertex
distance[i]=cost[0][i];
Choose a vertex w, such that distance[w] is minimum and visited[w] is 0. Markvisited[w] as 1.
7. Recalculate the shortest distance of remaining vertices from the source.
8. Only, the vertices not marked as 1 in array visited[ ] should be considered for
recalculation of distance. i.e. for each vertex v
if(visited[v]==0)
distance[v]=min(distance[v]
distance[w]+cost[w][v])
9. Stop
Program
/* Dijkstra’s Shortest Path */
#include <stdio.h>
#include <conio.h>
#define INFINITY 9999
#define MAX 10
void dijkstra(int G[MAX][MAX], int n, int startnode);main()
int G[MAX][MAX], i, j, n, u; printf("Enter no. of vertices: ");scanf("%d", &n);
printf("Enter the adjacency matrix:\n"); for(i=0; i<n; i++)for(j=0; j<n; j++)
scanf("%d", &G[i][j]);printf("Enter the starting node: ");scanf("%d", &u);
dijkstra(G, n, u);
void dijkstra(int G[MAX][MAX], int n,int startnode)
int cost[MAX][MAX], distance[MAX], pred[MAX];
int visited[MAX],count, mindistance, nextnode, i, j; for(i=0; i<n; i++)for(j=0; j<n; j++)
if(G[i][j] == 0)
cost[i][j] = INFINITY;
else
for(i=0; i<n; i++)
cost[i][j] = G[i][j];
distance[i] = cost[startnode][i];pred[i] = startnode;
visited[i] = 0;
distance[startnode] = 0;
visited[startnode] = 1;
count = 1; while(count < n-1)
{
mindistance = INFINITY;
for(i=0; i<n; i++)
if(distance[i] < mindistance && !visited[i])
mindistance = distance[i];nextnode=i;
visited[nextnode] = 1;
for(i=0; i<n; i++)
if(!visited[i])
if(mindistance + cost[nextnode][i] < distance[i])
count++;
distance[i] = mindistance + cost[nextnode][i];
pred[i] = nextnode;
for(i=0; i<n; i++)
if(i != startnode)
printf("\nDistance to node%d = %d", i, distance[i]);
printf("\nPath = %d", i);j = i;
do
j = pred[j]; printf("<-%d", j);
} while(j != startnode);
}
Output
Enter no. of vertices: 5
Enter the adjacency matrix:
0 10 0 30 100
10 0 50 0 0
0 50 0 20 10
30 0 20 0 60
100 0 0 60 0
Enter the starting node: 0 Distance to
node1 = 10 Path = 1<-0
Distance to node2 = 50 Path =
2<-3<-0 Distance to node3 = 30
Path = 3<-0 Distance to node4
= 60 Path = 4<-2<-3<-0
Result
Thus Dijkstra's algorithm is used to find shortest path from a given vertex.
Ex.No.10 Depth First Search
Date.
Aim :
To perform Depth First Search for the given graph.
Algorithm:
Step 1: SET STATUS = 1 (ready state) for each node in G
Step 2: Push the starting node A on the stack and set its STATUS = 2 (waiting state)
Step 3: Repeat Steps 4 and 5 until STACK is empty
Step 4: Pop the top node N. Process it and set its STATUS = 3 (processed state)
Step 5: Push on the stack all the neighbors of N that are in the ready state (whose STATUS = 1) and set
their STATUS = 2 (waiting state)
[END OF LOOP]
Step 6: EXIT
Program :
// C code to implement above approach
#include <stdio.h>
#include <stdlib.h>
// Globally declared visited array
int vis[100];
// Graph structure to store number
// of vertices and edges and
// Adjacency matrix
struct Graph {
int V;
int E;
int** Adj;
};
// Function to input data of graph
struct Graph* adjMatrix()
struct Graph* G = (struct Graph*)
malloc(sizeof(struct Graph));
if (!G) {
printf("Memory Error\n");
return NULL;
G->V = 7;
G->E = 7;
G->Adj = (int**)malloc((G->V) * sizeof(int*));
for (int k = 0; k < G->V; k++) {
G->Adj[k] = (int*)malloc((G->V) * sizeof(int));
}
for (int u = 0; u < G->V; u++) {
for (int v = 0; v < G->V; v++) {
G->Adj[u][v] = 0;
G->Adj[0][1] = G->Adj[1][0] = 1;
G->Adj[0][2] = G->Adj[2][0] = 1;
G->Adj[1][3] = G->Adj[3][1] = 1;
G->Adj[1][4] = G->Adj[4][1] = 1;
G->Adj[1][5] = G->Adj[5][1] = 1;
G->Adj[1][6] = G->Adj[6][1] = 1;
G->Adj[6][2] = G->Adj[2][6] = 1;
return G;
// DFS function to print DFS traversal of graph
void DFS(struct Graph* G, int u)
vis[u] = 1;
printf("%d ", u);
for (int v = 0; v < G->V; v++) {
if (!vis[v] && G->Adj[u][v]) {
DFS(G, v);
}
// Function for DFS traversal
void DFStraversal(struct Graph* G)
for (int i = 0; i < 100; i++) {
vis[i] = 0;
for (int i = 0; i < G->V; i++) {
if (!vis[i]) {
DFS(G, i);
// Driver code
void main()
struct Graph* G;
G = adjMatrix();
DFStraversal(G);
Output :
0134562
Result :
To perform Depth First Search for the given graph is executed and verified.
Ex.No. 11 Quick sort
Date.
Aim :
To perfrom quick sort for the given array
Algorithm :
quickSort(array, leftmostIndex, rightmostIndex)
if (leftmostIndex < rightmostIndex)
pivotIndex <- partition(array,leftmostIndex, rightmostIndex)
quickSort(array, leftmostIndex, pivotIndex - 1)
quickSort(array, pivotIndex, rightmostIndex)
partition(array, leftmostIndex, rightmostIndex)
set rightmostIndex as pivotIndex
storeIndex <- leftmostIndex - 1
for i <- leftmostIndex + 1 to rightmostIndex
if element[i] < pivotElement
swap element[i] and element[storeIndex]
storeIndex++
swap pivotElement and element[storeIndex+1]
return storeIndex + 1
Program :
#include <stdio.h>
// Function to swap numbers
void swap(int* a, int* b)
int temp = *a;
*a = *b;
*b = temp;
//Partition Function
int partition(int arr[], int low, int high)
int pivot = arr[high];
int i = (low - 1);
int j;
for (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);
// Quick Sort function
void quicksort(int Arr[], int low, int high)
if (low < high) {
// pi = Partition index
int pi = partition(Arr, low, high);
quicksort(Arr, low, pi - 1);
quicksort(Arr, pi + 1, high);
// Main Function
int main()
int size = 5;
int array[size] = { 11,9,6,16,7 };
quicksort(array, 0, size - 1);
int i;
for(i = 0; i < size; i++) {
printf("%d ",array[i]);
}
Output:
6 7 9 11 16
N queens problems
/* C program to solve N Queen Problem using
backtracking */
#define N 4
#include <stdbool.h>
#include <stdio.h>
/* A utility function to print solution */
void printSolution(int board[N][N])
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
printf(" %d ", board[i][j]);
printf("\n");
bool isSafe(int board[N][N], int row, int col)
int i, j;
/* Check this row on left side */
for (i = 0; i < col; i++)
if (board[row][i])
return false;
/* Check upper diagonal on left side */
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return false;
/* Check lower diagonal on left side */
for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j])
return false;
return true;
/* A recursive utility function to solve N
Queen problem */
bool solveNQUtil(int board[N][N], int col)
/* base case: If all queens are placed
then return true */
if (col >= N)
return true;
/* Consider this column and try placing
this queen in all rows one by one */
for (int i = 0; i < N; i++) {
/* Check if the queen can be placed on
board[i][col] */
if (isSafe(board, i, col)) {
/* Place this queen in board[i][col] */
board[i][col] = 1;
/* recur to place rest of the queens */
if (solveNQUtil(board, col + 1))
return true;
/* If placing queen in board[i][col]
doesn't lead to a solution, then
remove queen from board[i][col] */
board[i][col] = 0; // BACKTRACK
/* If the queen cannot be placed in any row in
this column col then return false */
return false;
}
bool solveNQ()
int board[N][N] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };
if (solveNQUtil(board, 0) == false) {
printf("Solution does not exist");
return false;
printSolution(board);
return true;
// driver program to test above function
int main()
solveNQ();
return 0;
Output:
. . Q .
Q . . .
. . . Q
. Q . .
Floyd algorithm
include<stdio.h>
void floyd(int a[4][4], int n)
for(int k=0;k<n;k++)
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
if(a[i][j]>a[i][k]+a[k][j])
a[i][j]=a[i][k]+a[k][j];
printf("All Pairs Shortest Path is :\n");
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
printf("%d ",a[i][j]);
}
printf("\n");
int main()
int cost[4][4] = {{0, 3, 999, 4}, {8, 0, 2, 999}, {5, 999, 0, 1}, {2, 999, 999, 0}};
int n = 4;
floyd(cost,n);
Output:
Output
All Pairs Shortest Path is :
0354
5023
3601
2570
Warshall algorithm
#include<stdio.h>
#include<conio.h>
#include<math.h>
int max(int,int);
void warshal(int p[10][10],int n) {
int i,j,k;
for (k=1;k<=n;k++)
for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
p[i][j]=max(p[i][j],p[i][k]&&p[k][j]);
int max(int a,int b) {
if(a>b)
return(a); else
return(b);
void main() {
int p[10][10]= {
,n,e,u,v,i,j;
clrscr();
printf("\n Enter the number of vertices:");
scanf("%d",&n);
printf("\n Enter the number of edges:");
scanf("%d",&e);
for (i=1;i<=e;i++) {
printf("\n Enter the end vertices of edge %d:",i);
scanf("%d%d",&u,&v);
p[u][v]=1;
printf("\n Matrix of input data: \n");
for (i=1;i<=n;i++) {
for (j=1;j<=n;j++)
printf("%d\t",p[i][j]);
printf("\n");
warshal(p,n);
printf("\n Transitive closure: \n");
for (i=1;i<=n;i++) {
for (j=1;j<=n;j++)
printf("%d\t",p[i][j]);
printf("\n");
getch();
Output
Result
Maximum and minimum
/* structure is used to return two values from minMax() */
#include<stdio.h>
struct pair
{
int min;
int max;
};
struct pair getMinMax(int arr[], int n)
struct pair minmax;
int i;
/*If there is only one element then return it as min and max both*/
if (n == 1)
minmax.max = arr[0];
minmax.min = arr[0];
return minmax;
/* If there are more than one elements, then initialize min
and max*/
if (arr[0] > arr[1])
minmax.max = arr[0];
minmax.min = arr[1];
else
{
minmax.max = arr[1];
minmax.min = arr[0];
for (i = 2; i<n; i++)
if (arr[i] > minmax.max)
minmax.max = arr[i];
else if (arr[i] < minmax.min)
minmax.min = arr[i];
return minmax;
/* Driver program to test above function */
int main()
int arr[] = {1000, 11, 445, 1, 330, 3000};
int arr_size = 6;
struct pair minmax = getMinMax (arr, arr_size);
printf("nMinimum element is %d", minmax.min);
printf("nMaximum element is %d", minmax.max);
getchar();
}
Output
Minimum element is 1
Maximum element is 3000
Travelling salesman problem
#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;
int main()
takeInput();
printf("\n\nThe Path is:\n");
mincost(0); //passing 0 because starting vertex
printf("\n\nMinimum cost is %d\n ",cost);
return 0;
Output
Enter the number of villages: 4
Enter the Cost Matrix
Enter Elements of Row: 1
0413
Enter Elements of Row: 2
4021
Enter Elements of Row: 3
1205
Enter Elements of Row: 4
3150
The cost list is:
0413
4021
1205
3150
The Path is:
1—>3—>2—>4—>1
Minimum cost is 7
Randomized algorithms
// C program to find K'th smallest element
#include <stdio.h>
#include <stdlib.h>
// Compare function for qsort
int cmpfunc(const void* a, const void* b)
return (*(int*)a - *(int*)b);
// Function to return K'th smallest
// element in a given array
int kthSmallest(int arr[], int N, int K)
// Sort the given array
qsort(arr, N, sizeof(int), cmpfunc);
// Return k'th element in the sorted array
return arr[K - 1];
// Driver's code
int main()
int arr[] = { 12, 3, 5, 7, 19 };
int N = sizeof(arr) / sizeof(arr[0]), K = 2;
// Function call
printf("K'th smallest element is %d",
kthSmallest(arr, N, K));
return 0;
}
Output:
K'th smallest element is 5