Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Algorithm

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

SL DESCRIPTION PAGE DATE SIGNATURE

No.
1 Breadth First Search ( BFS )

2 Quick Sort

3 Merge Sort

4 Binary Search

5 Prim Algorithm

6 Kruskal Algorithm

7 Dijkstra`s Algorithm

8 Floyd Warshal Algorithm

9 Knapsack 0 / 1

10 Adjacency Matrix

11 Depth First Search ( DFS )

1
BFS (Breadth-First Search)
Algorithm :

1. Start with the initial node.

2. Mark the initial node as visited and enqueue it.

3. While the queue is not empty:

Dequeue a node from the queue.

If the dequeued node is the goal node, stop the search.

Otherwise, enqueue any successors (nodes that are directly connected to the dequeued node) that
have not yet been visited.

4. If the queue is empty, every node on the graph has been visited, or there is no path from the initial
node to the goal node.

5. If the goal node was found, return the path that was followed.

Program Code :

#include <stdio.h>

#include <stdlib.h>

struct node {

int vertex;

struct node* next;

};

struct adj_list {

struct node* head;

};

struct graph {

int num_vertices;

struct adj_list* adj_lists;

int* visited;

};

struct node* new_node(int vertex) {

struct node* new_node = (struct node*)malloc(sizeof(struct node));

new_node->vertex = vertex;

new_node->next = NULL;

2
return new_node;

struct graph* create_graph(int n) {

struct graph* graph = (struct graph*)malloc(sizeof(struct graph));

graph->num_vertices = n;

graph->adj_lists = (struct adj_list*)malloc(n * sizeof(struct adj_list));

graph->visited = (int*)malloc(n * sizeof(int));

int i;

for (i = 0; i< n; i++) {

graph->adj_lists[i].head = NULL;

graph->visited[i] = 0;

return graph;

void add_edge(struct graph* graph, int src, int dest) {

struct node* new_node1 = new_node(dest);

new_node1->next = graph->adj_lists[src].head;

graph->adj_lists[src].head = new_node1;

struct node* new_node2 = new_node(src);

new_node2->next = graph->adj_lists[dest].head;

graph->adj_lists[dest].head = new_node2;

void bfs(struct graph* graph, int v) {

int queue[1000];

int front = -1;

int rear = -1;

graph->visited[v] = 1;

queue[++rear] = v;

while (front != rear) {

int current_vertex = queue[++front];

printf("%d ", current_vertex);

3
struct node* temp = graph->adj_lists[current_vertex].head;

while (temp != NULL) {

int adj_vertex = temp->vertex;

if (graph->visited[adj_vertex] == 0) {

graph->visited[adj_vertex] = 1;

queue[++rear] = adj_vertex;

temp = temp->next;

int main()

struct graph* graph = create_graph(6);

add_edge(graph, 0, 1);

add_edge(graph, 0, 2);

add_edge(graph, 1, 3);

add_edge(graph, 1, 4);

add_edge(graph, 2, 4);

add_edge(graph, 3, 4);

add_edge(graph, 3, 5);

add_edge(graph, 4,5);

printf("BFS traversal starting from vertex 0: ");

bfs(graph, 0);

return 0;

4
Quick Sort
Algorithm :

QUICKSORT (array A, start, end)

1 if (start < end)

2{

3 p = partition(A, start, end)

4 QUICKSORT (A, start, p - 1)

5 QUICKSORT (A, p + 1, end)

6}

PARTITION (array A, start, end)

1 pivot ? A[end]

2 i ? start-1

3 for j ? start to end -1 {

4 do if (A[j] < pivot) {

5 then i ? i + 1

6 swap A[i] with A[j]

7 }}

8 swap A[i+1] with A[end]

9 return i+1

Program Code:

#include <stdio.h>

void swap(int* a, int* b) {

int t = *a;

*a = *b;

*b = t;

5
int partition(int arr[], int low, int high) {

int pivot = arr[high];

int i = (low - 1);

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

if (arr[j] < pivot) {

i++;

swap(&arr[i], &arr[j]);

swap(&arr[i + 1], &arr[high]);

return (i + 1);

void quickSort(int arr[], int low, int high) {

if (low < high) {

int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1);

quickSort(arr, pi + 1, high);

void printArray(int arr[], int size) {

int i;

for (i = 0; i < size; i++)

printf("%d ", arr[i]);

printf("\n");

int main() {

int arr[] = { 12, 17, 6, 25, 1, 5 };

int n = sizeof(arr) / sizeof(arr[0]);

quickSort(arr, 0, n - 1);

printf("Sorted array: \n");

6
printArray(arr, n);

return 0;

7
Merge Sort
Algorithm :

MERGE_SORT(arr, beg, end)

if beg < end

set mid = (beg + end)/2

MERGE_SORT(arr, beg, mid)

MERGE_SORT(arr, mid + 1, end)

MERGE (arr, beg, mid, end)

end of if

END MERGE_SORT

void merge(int a[], int beg, int mid, int end)

int i, j, k;

int n1 = mid - beg + 1;

int n2 = end - mid;

int LeftArray[n1], RightArray[n2];

for (int i = 0; i < n1; i++)

LeftArray[i] = a[beg + i];

for (int j = 0; j < n2; j++)

RightArray[j] = a[mid + 1 + j];

i = 0,

j = 0;

k = beg;

while (i < n1 && j < n2)

if(LeftArray[i] <= RightArray[j])

a[k] = LeftArray[i];

i++;

else

8
{

a[k] = RightArray[j];

j++;

k++;

while (i<n1)

a[k] = LeftArray[i];

i++;

k++;

while (j<n2)

a[k] = RightArray[j];

j++;

k++;

Program Code:

#include <stdio.h>

void merge(int a[], int beg, int mid, int end)

int i, j, k;

int n1 = mid - beg + 1;

int n2 = end - mid;

int LeftArray[n1], RightArray[n2];

for (int i = 0; i < n1; i++)

LeftArray[i] = a[beg + i];

for (int j = 0; j < n2; j++)

RightArray[j] = a[mid + 1 + j];

9
i = 0;

j = 0;

k = beg;

while (i < n1 && j < n2)

if(LeftArray[i] <= RightArray[j])

a[k] = LeftArray[i];

i++;

else

a[k] = RightArray[j];

j++;

k++;

while (i<n1)

a[k] = LeftArray[i];

i++;

k++;

while (j<n2)

a[k] = RightArray[j];

j++;

k++;

10
void mergeSort(int a[], int beg, int end)

if (beg < end)

int mid = (beg + end) / 2;

mergeSort(a, beg, mid);

mergeSort(a, mid + 1, end);

merge(a, beg, mid, end);

void printArray(int a[], int n)

int i;

for (i = 0; i < n; i++)

printf("%d ", a[i]);

printf("\n");

int main()

int a[] = { 12, 31, 25, 8, 32, 17, 40, 42 };

int n = sizeof(a) / sizeof(a[0]);

printf("Before sorting array elements are - \n");

printArray(a, n);

mergeSort(a, 0, n - 1);

printf("After sorting array elements are - \n");

printArray(a, n);

return 0;

11
12
Prim Algorithm
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 Code:

#include <stdio.h>

#include <limits.h>

#define vertices 5

int minimum_key(int k[], int mst[])

int minimum = INT_MAX, min,i;

for (i = 0; i < vertices; i++)

if (mst[i] == 0 && k[i] < minimum )

minimum = k[i], min = i;

return min;

void prim(int g[vertices][vertices])

int parent[vertices];

int k[vertices];

int mst[vertices];

int i, count,edge,v; /*Here 'v' is the vertex*/

for (i = 0; i < vertices; i++)

k[i] = INT_MAX;

mst[i] = 0;

13
k[0] = 0;

parent[0] = -1;

for (count = 0; count < vertices-1; count++)

edge = minimum_key(k, mst);

mst[edge] = 1;

for (v = 0; v < vertices; v++)

if (g[edge][v] && mst[v] == 0 && g[edge][v] < k[v])

parent[v] = edge, k[v] = g[edge][v];

printf("\n Edge \t Weight\n");

for (i = 1; i < vertices; i++)

printf(" %d <-> %d %d \n", parent[i], i, g[i][parent[i]]);

int main()

int g[vertices][vertices] = {{0, 0, 3, 0, 0},

{0, 0, 10, 4, 0},

{3, 10, 0, 2, 6},

{0, 4, 2, 0, 1},

{0, 0, 6, 1, 0},

};

prim(g);

return 0;

14
15
Kruskal Algorithm
Algorithm :

1.Sort all the edges according to weight in a non-decreasing order.

2.Initialize an empty set for the minimum spanning tree and an empty disjoint-set data structure.

3.Add the edge to the tree and combine the two sets that the edge's endpoints belong to in the
disjoint-set data structure for each edge in the sorted order if doing so does not result in a cycle.

4.Until all edges have been taken into account or the smallest spanning tree has n-1 edges-where n is
the number of nodes in the graph-repeat step 3 as necessary.

5.At the end of the algorithm, the minimum spanning tree will be the set of edges added to the tree in
step 3. The temporal complexity of Kruskal's algorithm, where E is the number of edges and V is the
number of vertices in the graph, is either O(ElogE) or O(ElogV).

Program Code :

#include <stdio.h>

#include <stdlib.h>

#define MAX_EDGES 1000

typedef struct Edge {

int src, dest, weight;

} Edge;

typedef struct Graph {

int V, E;

Edge edges[MAX_EDGES];

} Graph;

typedef struct Subset {

int parent, rank;

} Subset;

Graph* createGraph(int V, int E) {

Graph* graph = (Graph*) malloc(sizeof(Graph));

graph->V = V;

graph->E = E;

return graph;

int find(Subset subsets[], int i) {

16
if (subsets[i].parent != i) {

subsets[i].parent = find(subsets, subsets[i].parent);

return subsets[i].parent;

void Union(Subset subsets[], int x, int y) {

int xroot = find(subsets, x);

int yroot = find(subsets, y);

if (subsets[xroot].rank < subsets[yroot].rank) {

subsets[xroot].parent = yroot;

} else if (subsets[xroot].rank > subsets[yroot].rank) {

subsets[yroot].parent = xroot;

} else {

subsets[yroot].parent = xroot;

subsets[xroot].rank++;

int compare(const void* a, const void* b) {

Edge* a_edge = (Edge*) a;

Edge* b_edge = (Edge*) b;

return a_edge->weight - b_edge->weight;

void kruskalMST(Graph* graph) {

Edge mst[graph->V];

int e = 0, i = 0;

qsort(graph->edges, graph->E, sizeof(Edge), compare);

Subset* subsets = (Subset*) malloc(graph->V * sizeof(Subset));

17
for (int v = 0; v < graph->V; ++v) {

subsets[v].parent = v;

subsets[v].rank = 0;

while (e < graph->V - 1 && i < graph->E) {

Edge next_edge = graph->edges[i++];

int x = find(subsets, next_edge.src);

int y = find(subsets, next_edge.dest);

if (x != y) {

mst[e++] = next_edge;

Union(subsets, x, y);

printf("Minimum Spanning Tree:\n");

for (i = 0; i < e; ++i) {

printf("(%d, %d) -> %d\n", mst[i].src, mst[i].dest, mst[i].weight);

int main() {

int V, E;

printf("Enter number of vertices and edges: ");

scanf("%d %d", &V, &E);

Graph* graph = createGraph(V, E);

printf("Enter edges and their weights:\n");

for (int i = 0; i < E; ++i) {

scanf("%d %d %d", &graph->edges[i].src, &graph->edges[i].dest, &graph->edges[i].weight);

kruskalMST(graph);

return 0;

18
Output :

Enter number of vertices and edges: 5 7

Enter edges and their weights:

012

036

123

138

145

247

349

Minimum Spanning Tree:

(0, 1) -> 2

(1, 2) -> 3

(1, 4) -> 5

(0, 3) -> 6

19
Dijkstra`s Algorithm
Algorithm :

Step 1: First, we will mark the source node with a current distance of 0 and set the rest of the nodes to
INFINITY.

Step 2: We will then set the unvisited node with the smallest current distance as the current node,
suppose X.

Step 3: For each neighbor N of the current node X: We will then add the current distance of X with the
weight of the edge joining X-N. If it is smaller than the current distance of N, set it as the new current
distance of N.

Step 4: We will then mark the current node X as visited.

Step 5: We will repeat the process from 'Step 2' if there is any node unvisited left in the graph.

Program Code :

#include <stdio.h>

#define INF 9999

#define MAX 10

void DijkstraAlgorithm(int Graph[MAX][MAX], int size, int start);

void DijkstraAlgorithm(int Graph[MAX][MAX], int size, int start) {

int cost[MAX][MAX], distance[MAX], previous[MAX];

int visited_nodes[MAX], counter, minimum_distance, next_node, i, j;

for (i = 0; i < size; i++)

for (j = 0; j < size; j++)

if (Graph[i][j] == 0)

cost[i][j] = INF;

else

cost[i][j] = Graph[i][j];

for (i = 0; i < size; i++) {

distance[i] = cost[start][i];

previous[i] = start;

visited_nodes[i] = 0;

20
distance[start] = 0;

visited_nodes[start] = 1;

counter = 1;

while (counter < size - 1) {

minimum_distance = INF;

for (i = 0; i < size; i++)

if (distance[i] < minimum_distance && !visited_nodes[i]) {

minimum_distance = distance[i];

next_node = i;

visited_nodes[next_node] = 1;

for (i = 0; i < size; i++)

if (!visited_nodes[i])

if (minimum_distance + cost[next_node][i] < distance[i]) {

distance[i] = minimum_distance + cost[next_node][i];

previous[i] = next_node;

counter++;

for (i = 0; i < size; i++)

if (i != start) {

printf("\nDistance from the Source Node to %d: %d", i, distance[i]);

int main() {

int Graph[MAX][MAX], i, j, size, source;

size = 7;

Graph[0][0] = 0;

Graph[0][1] = 4;

Graph[0][2] = 0;

21
Graph[0][3] = 0;

Graph[0][4] = 0;

Graph[0][5] = 8;

Graph[0][6] = 0;

Graph[1][0] = 4;

Graph[1][1] = 0;

Graph[1][2] = 8;

Graph[1][3] = 0;

Graph[1][4] = 0;

Graph[1][5] = 11;

Graph[1][6] = 0;

Graph[2][0] = 0;

Graph[2][1] = 8;

Graph[2][2] = 0;

Graph[2][3] = 7;

Graph[2][4] = 0;

Graph[2][5] = 4;

Graph[2][6] = 0;

Graph[3][0] = 0;

Graph[3][1] = 0;

Graph[3][2] = 7;

Graph[3][3] = 0;

Graph[3][4] = 9;

Graph[3][5] = 14;

Graph[3][6] = 0;

Graph[4][0] = 0;

Graph[4][1] = 0;

22
Graph[4][2] = 0;

Graph[4][3] = 9;

Graph[4][4] = 0;

Graph[4][5] = 10;

Graph[4][6] = 2;

Graph[5][0] = 0;

Graph[5][1] = 0;

Graph[5][2] = 4;

Graph[5][3] = 14;

Graph[5][4] = 10;

Graph[5][5] = 0;

Graph[5][6] = 2;

Graph[6][0] = 0;

Graph[6][1] = 0;

Graph[6][2] = 0;

Graph[6][3] = 0;

Graph[6][4] = 2;

Graph[6][5] = 0;

Graph[6][6] = 1;

source = 0;

DijkstraAlgorithm(Graph, size, source);

return 0;

23
Floyd Warshall Algorithm
Algorithm :

1.Initialize a distance matrix D wherein D[i][j] represents the shortest distance between vertex i and
vertex j.

2.Set the diagonal entries of the matrix to 0, and all other entries to infinity.

3.For every area (u,v) inside the graph, replace the gap matrix to mirror the weight of the brink: D[u][v]
= weight(u,v).

4.For every vertex okay in the graph, bear in mind all pairs of vertices (i,j) and check if the path from i
to j through k is shorter than the current best path. If it is, update the gap matrix: D[i][j] = min(D[i][j],
D[i][k] D[k][j]).

5.After all iterations, the matrix D will contain the shortest course distances between all pairs of
vertices.

Program Code :

#include <stdio.h>

#define INF 2147483647

int n = 4;

void fillDistanceMatrix(int A[n][n], int D[n][n]) {

for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {

if (i == j)

D[i][j] = 0;

else if (A[i][j] == 0)

D[i][j] = INF;

else

D[i][j] = A[i][j];

void floydWarshall(int A[n][n], int D[n][n]) {

fillDistanceMatrix(A, D);

for (int k = 0; k < n; k++) {

for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {

24
if (D[i][k] < INF && D[k][j] < INF)

if (D[i][k] + D[k][j] < D[i][j])

D[i][j] = D[i][k] + D[k][j];

int main() {

int A[4][4] = {{0, 5, INF, 10},

{INF, 0, 3, INF},

{INF, INF, 0, 1},

{INF, INF, INF, 0}};

int D[4][4];

floydWarshall(A, D);

printf("Shortest distances between all pairs of vertices:\n");

for (int i = 0; i < 4; i++) {

for (int j = 0; j < 4; j++) {

if (D[i][j] == INF)

printf("%7s", "INF");

else

printf("%7d", D[i][j]);

printf("\n");

return 0;

25
26
Knapsack 0/1
Algorithm :

Initialize 1st column to

0'sFor w=0 to w {

B[0,w] = 0 }

Initialize 1st row to

0'sfor i = 1 to n {

B[1,0] = 0 }

For I =1 to n

for w = 0 to W

if w₁ <= w( //item i can be in the solution if v₁+ B[1-1,w-w₁] > B[i-1,w] B[1,w] = V + B[1-1,w- w₁]

else

B[i,w] B[i-1,w]}

else B[1,w] = B[i-1,w] // w₁ > W

Program Code :

#include<stdio.h>

int max(int a, int b)

if(a>b)

return a;

else

return b;

27
int knapsack(int W, int wt[], int val[], int n)

int i, w;

int knap[n+1][W+1];

for (i = 0; i <= n; i++)

for (w = 0; w <= W; w++)

if (i==0 || w==0)

knap[i][w] = 0;

else if

(wt[i-1] <= w)

knap[i][w] = max(val[i-1] + knap[i-1][w-wt[i-1]], knap[i-1][w]);

else

knap[i][w] = knap[i-1][w];

return knap[n][W];

int main() {

int val[] = {20, 25, 40};

int wt[] = {25, 20, 30};

int W = 50;

int n = sizeof(val)/sizeof(val[0]);

printf("The solution is : %d", knapsack(W, wt, val, n));

return 0;

OUTPUT :

The solution is : 65

28
Depth First Search ( DFS )
Algorithm :

Step 1: SET STATUS = 1 (ready state) for each node in

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

#include<stdio.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);

void DFS(int i)

int j; printf("\n%d",i);

visited[i]=1;

29
for(j=0;j<n;j++)

if(!visited[j]&&G[i][j]==1) DFS(j);

OUTPUT:

Enter the number of vertices:8

Enter adjecency matrix of the graph: 0 1 1 1 1 0 0 0

10000100

10000100

10000010

10000010

01100001

00011001

00000110

Process returned 8 (0 × 8) Execution time:64.785

30
Adjacency Matrix
Algorithm:

1.Create a 2D array(say Adj[N+1][N+1]) of size NxN and initialise all value of this matrix to zero.

2.For each edge in arr[][](say X and Y), Update value at Adj[X][Y] and Adj[Y][X] to 1, denotes that there
is a edge between X and Y.

3.Display the Adjacency Matrix after the above operation for all the pairs in arr[][].

Program Code:

#include <stdio.h>

int N, M;

void createAdjMatrix(int Adj[][N + 1], int arr[][2])

for (int i = 0; i < N + 1; i++)

31
{

for (int j = 0; j < N + 1; j++)

Adj[i][j] = 0;

for (int i = 0; i < M; i++)

int x = arr[i][0];

int y = arr[i][1];

Adj[x][y] = 1;

Adj[y][x] = 1;

void printAdjMatrix(int Adj[][N + 1])

for (int i = 1; i < N + 1; i++)

for (int j = 1; j < N + 1; j++)

printf("%d ", Adj[i][j]);

printf("\n");

int main()

N = 5;

int arr[][2] = { { 1, 2 }, { 2, 3 } { 4, 5 }, { 1, 5 } };

M = sizeof(arr) / sizeof(arr[0]);

int Adj[N + 1][N + 1];

32
createAdjMatrix(Adj, arr);

printAdjMatrix(Adj);

return 0;

Output:

01001

10100

01000

00001

10010

33

You might also like