Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 38

************************bubble sort************************************

#include <stdio.h>

void swap(int *xp, int *yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

// A function to implement bubble sort


void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)

// Last i elements are already in place


for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}

/* Function to print an array */


void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver program to test above functions


int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

// An optimized version of Bubble Sort


void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped;
for (i = 0; i < n-1; i++)
{
swapped = false;
for (j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
swap(&arr[j], &arr[j+1]);
swapped = true;
}
}

// IF no two elements were swapped by inner loop, then break


if (swapped == false)
break;
}
}

/* Function to print an array */


void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("n");
}

// Driver program to test above functions


int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

******************************selection sort ****************************************


#include <stdio.h>

void swap(int *xp, int *yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void selectionSort(int arr[], int n)


{
int i, j, min_idx;

// One by one move boundary of unsorted subarray


for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first element


swap(&arr[min_idx], &arr[i]);
}
}

/* Function to print an array */


void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver program to test above functions


int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

************************************insertion sort**********************************

#include <math.h>
#include <stdio.h>

/* Function to sort an array using insertion sort*/


void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;

/* Move elements of arr[0..i-1], that are


greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

// A utility function to print an array of size n


void printArray(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}

/* Driver program to test insertion sort */


int main()
{
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);

insertionSort(arr, n);
printArray(arr, n);

return 0;
}

*****************************merge sort **********************************************

#include<stdlib.h>
#include<stdio.h>

// Merges two subarrays of arr[].


// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;

/* create temp arrays */


int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];

/* Merge the temp arrays back into arr[l..r]*/


i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}

/* Copy the remaining elements of L[], if there


are any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}

/* Copy the remaining elements of R[], if there


are any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}

/* l is for left index and r is right index of the


sub-array of arr to be sorted */
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);

merge(arr, l, m, r);
}
}

/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}

/* Driver program to test above functions */


int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr)/sizeof(arr[0]);

printf("Given array is \n");


printArray(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);

printf("\nSorted array is \n");


printArray(arr, arr_size);
return 0;
}

**********************************heap sort**********************************

#include <iostream>

using namespace std;

// 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)
{
int largest = i; // Initialize largest as root
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2

// If left child is larger than root


if (l < n && arr[l] > arr[largest])
largest = l;

// If right child is larger than largest so far


if (r < n && arr[r] > arr[largest])
largest = r;

// 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 heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);

// One by one extract an element from heap


for (int i=n-1; i>=0; i--)
{
// Move current root to end
swap(arr[0], arr[i]);

// call max heapify on the reduced heap


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)
cout << arr[i] << " ";
cout << "\n";
}

// Driver program
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr)/sizeof(arr[0]);

heapSort(arr, n);

cout << "Sorted array is \n";


printArray(arr, n);
}
***************************quick sort****************************************

/* This function takes last element as pivot, places


the pivot element at its correct position in sorted
array, and places all smaller (smaller than pivot)
to left of pivot and all greater elements to right
of pivot */
int partition (int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element

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


{
// If current element is smaller than the pivot
if (arr[j] < pivot)
{
i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}

/* The main function that implements QuickSort


arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);

// Separately sort elements before


// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

/* Function to print an array */


void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("n");
}

// Driver program to test above functions


int main()
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr)/sizeof(arr[0]);
quickSort(arr, 0, n-1);
printf("Sorted array: n");
printArray(arr, n);
return 0;
}

***********************************radix sort****************************************

#include<iostream>
using namespace std;

// A utility function to get maximum value in arr[]


int getMax(int arr[], int n)
{
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}

// A function to do counting sort of arr[] according to


// the digit represented by exp.
void countSort(int arr[], int n, int exp)
{
int output[n]; // output array
int i, count[10] = {0};

// Store count of occurrences in count[]


for (i = 0; i < n; i++)
count[ (arr[i]/exp)%10 ]++;

// Change count[i] so that count[i] now contains actual


// position of this digit in output[]
for (i = 1; i < 10; i++)
count[i] += count[i - 1];

// Build the output array


for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
count[ (arr[i]/exp)%10 ]--;
}

// Copy the output array to arr[], so that arr[] now


// contains sorted numbers according to current digit
for (i = 0; i < n; i++)
arr[i] = output[i];
}

// The main function to that sorts arr[] of size n using


// Radix Sort
void radixsort(int arr[], int n)
{
// Find the maximum number to know number of digits
int m = getMax(arr, n);

// Do counting sort for every digit. Note that instead


// of passing digit number, exp is passed. exp is 10^i
// where i is current digit number
for (int exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
}

// A utility function to print an array


void print(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}

// Driver program to test above functions


int main()
{
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr)/sizeof(arr[0]);
radixsort(arr, n);
print(arr, n);
return 0;
}

****************************binary tree***************************************

struct node
{
int data;
struct node *left;
struct node *right;
};

/* newNode() allocates a new node with the given data and NULL left and
right pointers. */
struct node* newNode(int data)
{
// Allocate memory for new node
struct node* node = (struct node*)malloc(sizeof(struct node));
// Assign data to this node
node->data = data;

// Initialize left and right children as NULL


node->left = NULL;
node->right = NULL;
return(node);
}

int main()
{
/*create root*/
struct node *root = newNode(1);
/* following is the tree after above statement

1
/ \
NULL NULL
*/

root->left = newNode(2);
root->right = newNode(3);
/* 2 and 3 become left and right children of 1
1
/ \
2 3
/ \ / \
NULL NULL NULL NULL
*/

root->left->left = newNode(4);
/* 4 becomes left child of 2
1
/ \
2 3
/ \ / \
4 NULL NULL NULL
/ \
NULL NULL
*/

getchar();
return 0;
}

#include<stdio.h>
#include<conio.h>
typedef struct node
{
int data;
struct node *left;
struct node *right;
} node;

node *create()
{
node *p;
int x;
printf("Enter data(-1 for no node):");
scanf("%d",&x);

if(x==-1)
return NULL;

p=(node*)malloc(sizeof(node));
p->data=x;
printf("Enter left child of %d:\n",x);
p->left=create();
printf("Enter right child of %d:\n",x);
p->right=create();
return p;
}

void preorder(node *t)


{
if(t!=NULL)
{
printf(" %d",t->data);
preorder(t->left);
preorder(t->right);
}
}
void inorder(node *t)
{
if(t!=NULL)
{
inorder(t->left);
printf(" %d",t->data);
inorder(t->right);
}
}
void postorder(node *t)
{
if(t!=NULL)
{
postorder(t->left);
postorder(t->right);
printf(" %d",t->data);
}
}
void main()
{
node *root;
clrscr();
root=create();
printf("\nThe preorder traversal of tree is: ");
preorder(root);
printf("\nThe inorder traversal of tree is: ");
inorder(root);
printf("\nThe postorder traversal of tree is: ");
postorder(root);
getch();
}

**************************Binary search tree***************************************

#include<stdio.h>
#include<stdlib.h>

struct node
{
int key;
struct node *left, *right;
};

// A utility function to create a new BST node


struct node *newNode(int item)
{
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}

// A utility function to do inorder traversal of BST


void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d \n", root->key);
inorder(root->right);
}
}

/* A utility function to insert a new node with given key in BST */


struct node* insert(struct node* node, int key)
{
/* If the tree is empty, return a new node */
if (node == NULL) return newNode(key);

/* Otherwise, recur down the tree */


if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);

/* return the (unchanged) node pointer */


return node;
}

// Driver Program to test above functions


int main()
{
/* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80 */
struct node *root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);

// print inoder traversal of the BST


inorder(root);

return 0;
}

struct node* search(struct node* root, int key)


{
// Base Cases: root is null or key is present at root
if (root == NULL || root->key == key)
return root;

// Key is greater than root's key


if (root->key < key)
return search(root->right, key);

// Key is smaller than root's key


return search(root->left, key);
}

********************************binary search tree**************************

1. /*
2. * C Program to Construct a Binary Search Tree and perform deletion, inorder
traversal on it
3. */
4. #include <stdio.h>
5. #include <stdlib.h>
6.
7. struct btnode
8. {
9. int value;
10. struct btnode *l;
11. struct btnode *r;
12. }*root = NULL, *temp = NULL, *t2, *t1;
13.
14. void delete1();
15. void insert();
16. void delete();
17. void inorder(struct btnode *t);
18. void create();
19. void search(struct btnode *t);
20. void preorder(struct btnode *t);
21. void postorder(struct btnode *t);
22. void search1(struct btnode *t,int data);
23. int smallest(struct btnode *t);
24. int largest(struct btnode *t);
25.
26. int flag = 1;
27.
28. void main()
29. {
30. int ch;
31.
32. printf("\nOPERATIONS ---");
33. printf("\n1 - Insert an element into tree\n");
34. printf("2 - Delete an element from the tree\n");
35. printf("3 - Inorder Traversal\n");
36. printf("4 - Preorder Traversal\n");
37. printf("5 - Postorder Traversal\n");
38. printf("6 - Exit\n");
39. while(1)
40. {
41. printf("\nEnter your choice : ");
42. scanf("%d", &ch);
43. switch (ch)
44. {
45. case 1:
46. insert();
47. break;
48. case 2:
49. delete();
50. break;
51. case 3:
52. inorder(root);
53. break;
54. case 4:
55. preorder(root);
56. break;
57. case 5:
58. postorder(root);
59. break;
60. case 6:
61. exit(0);
62. default :
63. printf("Wrong choice, Please enter correct choice ");
64. break;
65. }
66. }
67. }
68.
69. /* To insert a node in the tree */
70. void insert()
71. {
72. create();
73. if (root == NULL)
74. root = temp;
75. else
76. search(root);
77. }
78.
79. /* To create a node */
80. void create()
81. {
82. int data;
83.
84. printf("Enter data of node to be inserted : ");
85. scanf("%d", &data);
86. temp = (struct btnode *)malloc(1*sizeof(struct btnode));
87. temp->value = data;
88. temp->l = temp->r = NULL;
89. }
90.
91. /* Function to search the appropriate position to insert the new node */
92. void search(struct btnode *t)
93. {
94. if ((temp->value > t->value) && (t->r != NULL)) /* value more than
root node value insert at right */
95. search(t->r);
96. else if ((temp->value > t->value) && (t->r == NULL))
97. t->r = temp;
98. else if ((temp->value < t->value) && (t->l != NULL)) /* value less t
han root node value insert at left */
99. search(t->l);
100. else if ((temp->value < t->value) && (t->l == NULL))
101. t->l = temp;
102. }
103.
104. /* recursive function to perform inorder traversal of tree */
105. void inorder(struct btnode *t)
106. {
107. if (root == NULL)
108. {
109. printf("No elements in a tree to display");
110. return;
111. }
112. if (t->l != NULL)
113. inorder(t->l);
114. printf("%d -> ", t->value);
115. if (t->r != NULL)
116. inorder(t->r);
117. }
118.
119. /* To check for the deleted node */
120. void delete()
121. {
122. int data;
123.
124. if (root == NULL)
125. {
126. printf("No elements in a tree to delete");
127. return;
128. }
129. printf("Enter the data to be deleted : ");
130. scanf("%d", &data);
131. t1 = root;
132. t2 = root;
133. search1(root, data);
134. }
135.
136. /* To find the preorder traversal */
137. void preorder(struct btnode *t)
138. {
139. if (root == NULL)
140. {
141. printf("No elements in a tree to display");
142. return;
143. }
144. printf("%d -> ", t->value);
145. if (t->l != NULL)
146. preorder(t->l);
147. if (t->r != NULL)
148. preorder(t->r);
149. }
150.
151. /* To find the postorder traversal */
152. void postorder(struct btnode *t)
153. {
154. if (root == NULL)
155. {
156. printf("No elements in a tree to display ");
157. return;
158. }
159. if (t->l != NULL)
160. postorder(t->l);
161. if (t->r != NULL)
162. postorder(t->r);
163. printf("%d -> ", t->value);
164. }
165.
166. /* Search for the appropriate position to insert the new node */
167. void search1(struct btnode *t, int data)
168. {
169. if ((data>t->value))
170. {
171. t1 = t;
172. search1(t->r, data);
173. }
174. else if ((data < t->value))
175. {
176. t1 = t;
177. search1(t->l, data);
178. }
179. else if ((data==t->value))
180. {
181. delete1(t);
182. }
183. }
184.
185. /* To delete a node */
186. void delete1(struct btnode *t)
187. {
188. int k;
189.
190. /* To delete leaf node */
191. if ((t->l == NULL) && (t->r == NULL))
192. {
193. if (t1->l == t)
194. {
195. t1->l = NULL;
196. }
197. else
198. {
199. t1->r = NULL;
200. }
201. t = NULL;
202. free(t);
203. return;
204. }
205.
206. /* To delete node having one left hand child */
207. else if ((t->r == NULL))
208. {
209. if (t1 == t)
210. {
211. root = t->l;
212. t1 = root;
213. }
214. else if (t1->l == t)
215. {
216. t1->l = t->l;
217.
218. }
219. else
220. {
221. t1->r = t->l;
222. }
223. t = NULL;
224. free(t);
225. return;
226. }
227.
228. /* To delete node having right hand child */
229. else if (t->l == NULL)
230. {
231. if (t1 == t)
232. {
233. root = t->r;
234. t1 = root;
235. }
236. else if (t1->r == t)
237. t1->r = t->r;
238. else
239. t1->l = t->r;
240. t == NULL;
241. free(t);
242. return;
243. }
244.
245. /* To delete node having two child */
246. else if ((t->l != NULL) && (t->r != NULL))
247. {
248. t2 = root;
249. if (t->r != NULL)
250. {
251. k = smallest(t->r);
252. flag = 1;
253. }
254. else
255. {
256. k =largest(t->l);
257. flag = 2;
258. }
259. search1(root, k);
260. t->value = k;
261. }
262.
263. }
264.
265. /* To find the smallest element in the right sub tree */
266. int smallest(struct btnode *t)
267. {
268. t2 = t;
269. if (t->l != NULL)
270. {
271. t2 = t;
272. return(smallest(t->l));
273. }
274. else
275. return (t->value);
276. }
277.
278. /* To find the largest element in the left sub tree */
279. int largest(struct btnode *t)
280. {
281. if (t->r != NULL)
282. {
283. t2 = t;
284. return(largest(t->r));
285. }
286. else
287. return(t->value);
288. }

************************************splay tree***************************************
#include<stdio.h>

typedef struct node


{
int data;
struct node *left,*right;
int ht;
}node;

node *insert(node *,int);


node *Delete(node *,int);
void preorder(node *);
void inorder(node *);
int height( node *);
node *rotateright(node *);
node *rotateleft(node *);
node *RR(node *);
node *LL(node *);
node *LR(node *);
node *RL(node *);
int BF(node *);

int main()
{
node *root=NULL;
int x,n,i,op;

do
{
printf("\n1)Create:");
printf("\n2)Insert:");
printf("\n3)Delete:");
printf("\n4)Print:");
printf("\n5)Quit:");
printf("\n\nEnter Your Choice:");
scanf("%d",&op);

switch(op)
{
case 1: printf("\nEnter no. of elements:");
scanf("%d",&n);
printf("\nEnter tree data:");
root=NULL;
for(i=0;i<n;i++)
{
scanf("%d",&x);
root=insert(root,x);
}
break;

case 2: printf("\nEnter a data:");


scanf("%d",&x);
root=insert(root,x);
break;

case 3: printf("\nEnter a data:");


scanf("%d",&x);
root=Delete(root,x);
break;

case 4: printf("\nPreorder sequence:\n");


preorder(root);
printf("\n\nInorder sequence:\n");
inorder(root);
printf("\n");
break;
}
}while(op!=5);

return 0;
}

node * insert(node *T,int x)


{
if(T==NULL)
{
T=(node*)malloc(sizeof(node));
T->data=x;
T->left=NULL;
T->right=NULL;
}
else
if(x > T->data) // insert in right subtree
{
T->right=insert(T->right,x);
if(BF(T)==-2)
if(x>T->right->data)
T=RR(T);
else
T=RL(T);
}
else
if(x<T->data)
{
T->left=insert(T->left,x);
if(BF(T)==2)
if(x < T->left->data)
T=LL(T);
else
T=LR(T);
}

T->ht=height(T);

return(T);
}

node * Delete(node *T,int x)


{
node *p;

if(T==NULL)
{
return NULL;
}
else
if(x > T->data) // insert in right subtree
{
T->right=Delete(T->right,x);
if(BF(T)==2)
if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);
}
else
if(x<T->data)
{
T->left=Delete(T->left,x);
if(BF(T)==-2) //Rebalance during windup
if(BF(T->right)<=0)
T=RR(T);
else
T=RL(T);
}
else
{
//data to be deleted is found
if(T->right!=NULL)
{ //delete its inorder succesor
p=T->right;

while(p->left!= NULL)
p=p->left;

T->data=p->data;
T->right=Delete(T->right,p->data);

if(BF(T)==2)//Rebalance during windup


if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);\
}
else
return(T->left);
}
T->ht=height(T);
return(T);
}

int height(node *T)


{
int lh,rh;
if(T==NULL)
return(0);

if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;

if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;

if(lh>rh)
return(lh);

return(rh);
}

node * rotateright(node *x)


{
node *y;
y=x->left;
x->left=y->right;
y->right=x;
x->ht=height(x);
y->ht=height(y);
return(y);
}

node * rotateleft(node *x)


{
node *y;
y=x->right;
x->right=y->left;
y->left=x;
x->ht=height(x);
y->ht=height(y);
return(y);
}

node * RR(node *T)


{
T=rotateleft(T);
return(T);
}

node * LL(node *T)


{
T=rotateright(T);
return(T);
}

node * LR(node *T)


{
T->left=rotateleft(T->left);
T=rotateright(T);

return(T);
}

node * RL(node *T)


{
T->right=rotateright(T->right);
T=rotateleft(T);
return(T);
}

int BF(node *T)


{
int lh,rh;
if(T==NULL)
return(0);

if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;

if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;

return(lh-rh);
}

void preorder(node *T)


{
if(T!=NULL)
{
printf("%d(Bf=%d)",T->data,BF(T));
preorder(T->left);
preorder(T->right);
}
}

void inorder(node *T)


{
if(T!=NULL)
{
inorder(T->left);
printf("%d(Bf=%d)",T->data,BF(T));
inorder(T->right);
}
}

*********************************graph**********************************************\
DFS(Adjaency Matrix)
#include<stdio.h>

void DFS(int);
int G[10][10],visited[10],n; //n is no of vertices and graph is sorted in array G[10][10]

void main()
{
int i,j;
printf("Enter number of vertices:");

scanf("%d",&n);

//read the adjecency matrix


printf("\nEnter adjecency matrix of the graph:");

for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);

//visited is initialized to zero


for(i=0;i<n;i++)
visited[i]=0;

DFS(0);
}

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);
}

********************** dfs(adjacency list)***


#include<stdio.h>
#include<stdlib.h>

typedef struct node


{
struct node *next;
int vertex;
}node;

node *G[20];
//heads of linked list
int visited[20];
int n;
void read_graph();
//create adjacency list
void insert(int,int);
//insert an edge (vi,vj) in te adjacency list
void DFS(int);

void main()
{
int i;
read_graph();
//initialised visited to 0

for(i=0;i<n;i++)
visited[i]=0;

DFS(0);
}

void DFS(int i)
{
node *p;

printf("\n%d",i);
p=G[i];
visited[i]=1;
while(p!=NULL)
{
i=p->vertex;

if(!visited[i])
DFS(i);
p=p->next;
}
}

void read_graph()
{
int i,vi,vj,no_of_edges;
printf("Enter number of vertices:");

scanf("%d",&n);

//initialise G[] with a null

for(i=0;i<n;i++)
{
G[i]=NULL;
//read edges and insert them in G[]

printf("Enter number of edges:");


scanf("%d",&no_of_edges);

for(i=0;i<no_of_edges;i++)
{
printf("Enter an edge(u,v):");
scanf("%d%d",&vi,&vj);
insert(vi,vj);
}
}
}

void insert(int vi,int vj)


{
node *p,*q;

//acquire memory for the new node


q=(node*)malloc(sizeof(node));
q->vertex=vj;
q->next=NULL;

//insert the node in the linked list number vi


if(G[vi]==NULL)
G[vi]=q;
else
{
//go to end of the linked list
p=G[vi];

while(p->next!=NULL)
p=p->next;
p->next=q;
}
}

*******************************bfs***************************************
#include<stdio.h>
#include<stdlib.h>

#define MAX 100

#define initial 1
#define waiting 2
#define visited 3

int n;
int adj[MAX][MAX];
int state[MAX];
void create_graph();
void BF_Traversal();
void BFS(int v);

int queue[MAX], front = -1,rear = -1;


void insert_queue(int vertex);
int delete_queue();
int isEmpty_queue();

int main()
{
create_graph();
BF_Traversal();
return 0;
}

void BF_Traversal()
{
int v;

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


state[v] = initial;

printf("Enter Start Vertex for BFS: \n");


scanf("%d", &v);
BFS(v);
}

void BFS(int v)
{
int i;

insert_queue(v);
state[v] = waiting;

while(!isEmpty_queue())
{
v = delete_queue( );
printf("%d ",v);
state[v] = visited;

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


{
if(adj[v][i] == 1 && state[i] == initial)
{
insert_queue(i);
state[i] = waiting;
}
}
}
printf("\n");
}

void insert_queue(int vertex)


{
if(rear == MAX-1)
printf("Queue Overflow\n");
else
{
if(front == -1)
front = 0;
rear = rear+1;
queue[rear] = vertex ;
}
}

int isEmpty_queue()
{
if(front == -1 || front > rear)
return 1;
else
return 0;
}

int delete_queue()
{
int delete_item;
if(front == -1 || front > rear)
{
printf("Queue Underflow\n");
exit(1);
}

delete_item = queue[front];
front = front+1;
return delete_item;
}

void create_graph()
{
int count,max_edge,origin,destin;

printf("Enter number of vertices : ");


scanf("%d",&n);
max_edge = n*(n-1);

for(count=1; count<=max_edge; count++)


{
printf("Enter edge %d( -1 -1 to quit ) : ",count);
scanf("%d %d",&origin,&destin);

if((origin == -1) && (destin == -1))


break;

if(origin>=n || destin>=n || origin<0 || destin<0)


{
printf("Invalid edge!\n");
count--;
}
else
{
adj[origin][destin] = 1;
}
}
}

*************************************basic operation*********************************
#include <stdio.h>
#include <stdlib.h>

// A structure to represent an adjacency list node


struct AdjListNode
{
int dest;
struct AdjListNode* next;
};

// A structure to represent an adjacency list


struct AdjList
{
struct AdjListNode *head;
};

// A structure to represent a graph. A graph


// is an array of adjacency lists.
// Size of array will be V (number of vertices
// in graph)
struct Graph
{
int V;
struct AdjList* array;
};

// A utility function to create a new adjacency list node


struct AdjListNode* newAdjListNode(int dest)
{
struct AdjListNode* newNode =
(struct AdjListNode*) malloc(sizeof(struct AdjListNode));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}

// A utility function that creates a graph of V vertices


struct Graph* createGraph(int V)
{
struct Graph* graph =
(struct Graph*) malloc(sizeof(struct Graph));
graph->V = V;

// Create an array of adjacency lists. Size of


// array will be V
graph->array =
(struct AdjList*) malloc(V * sizeof(struct AdjList));

// Initialize each adjacency list as empty by


// making head as NULL
int i;
for (i = 0; i < V; ++i)
graph->array[i].head = NULL;

return graph;
}

// Adds an edge to an undirected graph


void addEdge(struct Graph* graph, int src, int dest)
{
// Add an edge from src to dest. A new node is
// added to the adjacency list of src. The node
// is added at the begining
struct AdjListNode* newNode = newAdjListNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;

// Since graph is undirected, add an edge from


// dest to src also
newNode = newAdjListNode(src);
newNode->next = graph->array[dest].head;
graph->array[dest].head = newNode;
}

// A utility function to print the adjacency list


// representation of graph
void printGraph(struct Graph* graph)
{
int v;
for (v = 0; v < graph->V; ++v)
{
struct AdjListNode* pCrawl = graph->array[v].head;
printf("\n Adjacency list of vertex %d\n head ", v);
while (pCrawl)
{
printf("-> %d", pCrawl->dest);
pCrawl = pCrawl->next;
}
printf("\n");
}
}

// Driver program to test above functions


int main()
{
// create the graph given in above fugure
int V = 5;
struct Graph* graph = createGraph(V);
addEdge(graph, 0, 1);
addEdge(graph, 0, 4);
addEdge(graph, 1, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 3);
addEdge(graph, 3, 4);

// print the adjacency list representation of the above graph


printGraph(graph);

return 0;
}

*******************************queue***************************************
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

// A structure to represent a queue


struct Queue
{
int front, rear, size;
unsigned capacity;
int* array;
};

// function to create a queue of given capacity.


// It initializes size of queue as 0
struct Queue* createQueue(unsigned capacity)
{
struct Queue* queue = (struct Queue*) malloc(sizeof(struct Queue));
queue->capacity = capacity;
queue->front = queue->size = 0;
queue->rear = capacity - 1; // This is important, see the enqueue
queue->array = (int*) malloc(queue->capacity * sizeof(int));
return queue;
}

// Queue is full when size becomes equal to the capacity


int isFull(struct Queue* queue)
{ return (queue->size == queue->capacity); }

// Queue is empty when size is 0


int isEmpty(struct Queue* queue)
{ return (queue->size == 0); }

// Function to add an item to the queue.


// It changes rear and size
void enqueue(struct Queue* queue, int item)
{
if (isFull(queue))
return;
queue->rear = (queue->rear + 1)%queue->capacity;
queue->array[queue->rear] = item;
queue->size = queue->size + 1;
printf("%d enqueued to queue\n", item);
}

// Function to remove an item from queue.


// It changes front and size
int dequeue(struct Queue* queue)
{
if (isEmpty(queue))
return INT_MIN;
int item = queue->array[queue->front];
queue->front = (queue->front + 1)%queue->capacity;
queue->size = queue->size - 1;
return item;
}

// Function to get front of queue


int front(struct Queue* queue)
{
if (isEmpty(queue))
return INT_MIN;
return queue->array[queue->front];
}

// Function to get rear of queue


int rear(struct Queue* queue)
{
if (isEmpty(queue))
return INT_MIN;
return queue->array[queue->rear];
}
// Driver program to test above functions./
int main()
{
struct Queue* queue = createQueue(1000);

enqueue(queue, 10);
enqueue(queue, 20);
enqueue(queue, 30);
enqueue(queue, 40);

printf("%d dequeued from queue\n\n", dequeue(queue));

printf("Front item is %d\n", front(queue));


printf("Rear item is %d\n", rear(queue));

return 0;
}

********************************stack****************************************
#include <stdio.h>

int MAXSIZE = 8;
int stack[8];
int top = -1;

int isempty() {

if(top == -1)
return 1;
else
return 0;
}

int isfull() {

if(top == MAXSIZE)
return 1;
else
return 0;
}

int peek() {
return stack[top];
}

int pop() {
int data;

if(!isempty()) {
data = stack[top];
top = top - 1;
return data;
} else {
printf("Could not retrieve data, Stack is empty.\n");
}
}

int push(int data) {

if(!isfull()) {
top = top + 1;
stack[top] = data;
} else {
printf("Could not insert data, Stack is full.\n");
}
}

int main() {
// push items on to the stack
push(3);
push(5);
push(9);
push(1);
push(12);
push(15);

printf("Element at top of the stack: %d\n" ,peek());


printf("Elements: \n");

// print stack data


while(!isempty()) {
int data = pop();
printf("%d\n",data);
}

printf("Stack full: %s\n" , isfull()?"true":"false");


printf("Stack empty: %s\n" , isempty()?"true":"false");

return 0;
}

***********************************linked list*******************
1. #include<stdio.h>
2. #include<stdlib.h>
3.
4. struct node
5. {
6. int data;
7. struct node *next;
8. };
9.
10. void display(struct node* head)
11. {
12. struct node *temp = head;
13. printf("\n\nList elements are - \n");
14. while(temp != NULL)
15. {
16. printf("%d --->",temp->data);
17. temp = temp->next;
18. }
19. }
20.
21. void insertAtMiddle(struct node *head, int position, int value) {
22. struct node *temp = head;
23. struct node *newNode;
24. newNode = malloc(sizeof(struct node));
25. newNode->data = value;
26.
27. int i;
28.
29. for(i=2; inext != NULL) {
30. temp = temp->next;
31. }
32. }
33. newNode->next = temp->next;
34. temp->next = newNode;
35. }
36.
37. void insertAtFront(struct node** headRef, int value) {
38. struct node* head = *headRef;
39.
40. struct node *newNode;
41. newNode = malloc(sizeof(struct node));
42. newNode->data = value;
43. newNode->next = head;
44. head = newNode;
45.
46. *headRef = head;
47. }
48.
49. void insertAtEnd(struct node* head, int value){
50. struct node *newNode;
51. newNode = malloc(sizeof(struct node));
52. newNode->data = value;
53. newNode->next = NULL;
54.
55. struct node *temp = head;
56. while(temp->next != NULL){
57. temp = temp->next;
58. }
59. temp->next = newNode;
60. }
61.
62. void deleteFromFront(struct node** headRef){
63. struct node* head = *headRef;
64. head = head->next;
65. *headRef = head;
66. }
67.
68. void deleteFromEnd(struct node* head){
69. struct node* temp = head;
70. while(temp->next->next!=NULL){
71. temp = temp->next;
72. }
73. temp->next = NULL;
74. }
75.
76. void deleteFromMiddle(struct node* head, int position){
77. struct node* temp = head;
78. int i;
79. for(i=2; inext != NULL) {
80. temp = temp->next;
81. }
82. }
83.
84. temp->next = temp->next->next;
85. }
86.
87. int main() {
88. /* Initialize nodes */
89. struct node *head;
90. struct node *one = NULL;
91. struct node *two = NULL;
92. struct node *three = NULL;
93.
94. /* Allocate memory */
95. one = malloc(sizeof(struct node));
96. two = malloc(sizeof(struct node));
97. three = malloc(sizeof(struct node));
98.
99. /* Assign data values */
100. one->data = 1;
101. two->data = 2;
102. three->data = 3;
103.
104. /* Connect nodes */
105. one->next = two;
106. two->next = three;
107. three->next = NULL;
108.
109. /* Save address of first node in head */
110. head = one;
111.
112. display(head); // 1 --->2 --->3 --->
113.
114. insertAtFront(&head, 4);
115. display(head); // 4 --->1 --->2 --->3 --->
116.
117. deleteFromFront(&head);
118. display(head); // 1 --->2 --->3 --->
119.
120. insertAtEnd(head, 5);
121. display(head); // 1 --->2 --->3 --->5 --->
122.
123. deleteFromEnd(head);
124. display(head); // 1 --->2 --->3 --->
125.
126. int position = 3;
127. insertAtMiddle(head, position, 10);
128. display(head); // 1 --->2 --->10 --->3 --->
129.
130. deleteFromMiddle(head, position);
131. display(head); // 1 --->2 --->3 --->
132. }

You might also like