Top Banner
1 Lord Krishna College of Engineering, Ghaziabad Department of Computer Science and Engineering Lab Manual DAA Submitted by Submitted to:
43

Final DAA Lab Manual

Jan 02, 2016

Download

Documents

Gina Barrera
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Final DAA Lab Manual

1

Lord Krishna College of Engineering,

Ghaziabad

Department of

Computer Science and Engineering

Lab Manual

DAA

Submitted by Submitted to:

Mr. Dharmveer Singh

Asstt.Proff.

Page 2: Final DAA Lab Manual

2

INDEX

S.No. Name of Program Page No.

1. To implement the Program of Binary Search using C. 3

2. To implement the Program of Linear Search (Sequential Search) using C.

5

3. To implement the Program of Bubble sort in C. 7

4. To implement the Program of Insertion sort in C. 10

5. To implement the Program of Merge sort in C. 13

6. To implement the Program of Quick sort in C. 16

7. To implement the Program of Merging two sorted array into a single array using C.

20

8. To implement the Program of Radix sort in C. 22

9. To implement the Program of Selection sort in C. 27

10. To implement the Program of Binary Search Tree with creation, insertion & Deletion operation in C.

30

Page 3: Final DAA Lab Manual

3

Program 1: To implement the Program of Binary Search using C.

Object:

Write a program for finding out an element using Binary Search Algorithm in ‘C’ language.

Theory:

A Binary search is an algorithm for locating the position of an element in a sorted list.[1][2] It inspects the middle element of the sorted list: if equal to the sought value, then the position has been found; otherwise, the upper half or lower half is chosen for further searching based on whether the sought value is greater than or less than the middle element. The method reduces the number of elements needed to be checked by a factor of two each time, and finds the sought value if it exists in the list or if not determines "not present", in logarithmic time. A binary search is a dichotomic divide and conquer search algorithm.

Viewing the comparison as a subtraction of the sought value from the middle element, only the sign of the difference is inspected: there is no attempt at an interpolation search based on the size of the difference.

Algorithm

mid = (beg + end)/2while (a[mid] != item) && (beg <= end)

if a[mid] > itemend = mid – 1;

else beg = mid + 1;

mid = (beg + end)/2;if (a[mid] = = item)

printf(“Item found”);else

printf(“Item not found”);

CODE:

#include <stdio.h>

Page 4: Final DAA Lab Manual

4

#include<conio.h>

main(){

int arr[20],start,end,middle,n,i,item;clrscr();printf("How many elements you want to enter in the array : ");scanf("%d",&n);for(i=0; i < n; i++){

printf("Enter element %d : ",i+1);scanf("%d",&arr[i]);

}printf("Enter the element to be searched : ");scanf("%d",&item);start=0;end=n-1;middle=(start+end)/2;while(item != arr[middle] && start <= end){

if(item > arr[middle])start=middle+1;

elseend=middle-1;

middle=(start+end)/2;}if(item==arr[middle])

printf("%d found at position %d\n",item,middle+1);if(start>end)

printf("%d not found in array\n",item);getch();

}

INPUT & OUTPUT:

How many elements you want to enter in the array : 5Enter element 1 : 20Enter element 2 : 40Enter element 3 : 60Enter element 4 : 80Enter element 5 : 100

Page 5: Final DAA Lab Manual

5

Enter the element to be searched : 8080 found at position 4

Program 2 : To implement the Program of Linear Search using C.

Object:

Write a program for finding out an element using Linear Search Algorithm in ‘C’ language.

Theory:

linear search or sequential search is a method for finding a particular value in a list, that consists of checking every one of its elements, one at a time and in sequence, until the desired one is found.[1]

Linear search is the simplest search algorithm; it is a special case of brute-force search. Its worst case cost is proportional to the number of elements in the list; and so is its expected cost, if all list elements are equally likely to be searched for. Therefore, if the list has more than a few elements, other methods (such as binary search or hashing) may be much more efficient.

For a list with n items, the best case is when the value is equal to the first element of the list, in which case only one comparison is needed. The worst case is when the value is not in the list (or occurs only once at the end of the list), in which case n comparisons are needed.

If the value being sought occurs k times in the list, and all orderings of the list are equally likely, the expected number of comparisons is

Asymptotically, therefore, the worst-case cost and the expected cost of linear search are both

O (n).

Algorithm:

For each item in the list: if that item has the desired value, stop the search and return the item's location.

Page 6: Final DAA Lab Manual

6

Return Λ.

CODE:

# include<stdio.h>#include<conio.h>main(){

int arr[20],n,i,item;printf("How many elements you want to enter in the array : ");scanf("%d",&n);

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

printf("Enter element %d : ",i+1);scanf("%d", &arr[i]);

}printf("Enter the element to be searched : ");scanf("%d",&item);for(i=0;i < n;i++){

if(item == arr[i]){

printf("%d found at position %d\n",item,i+1);break;

}}/*End of for*/if(i == n)

printf("Item %d not found in array\n",item);

}INPUT & OUTPUT :

How many elements you want to enter in the array : 5Enter element 1 : 789Enter element 2 : 458Enter element 3 : 12Enter element 4 : 56Enter element 5 : 2Enter the element to be searched : 1212 found at position 3

Page 7: Final DAA Lab Manual

7

Program 3: To implement the Program of Insertion sort in C.

Object:-

Write a program for arranging elements in ascending order using Insertion Sort Algorithm in ‘C’ language.

Theory:-

It is a simple sorting algorithm, a comparison sort in which the sorted array is built one entry at a time.

It is much less efficient on large lists than more advanced algorithms such as Quick sort, Heap sort or Merge Sort.

Time Complexity: Worst Case = O(n2)Average Case = O(n2)Best Case = O(n)

It has simple implementation. It is efficient for small data sets. Adaptive, i.e. efficient for data sets that are already substantially sorted: the timke

complexity is O(n+d), where d is the number of inversions. Stable, i.e. does not change the relative order of elements with equal keys. In-place, i.e. only requires a constant amount O(1) of additional memory space. Online, i.e. can sort a list as it receives it. Insertion Sort always maintains two zeros in the array to be sorted: sorted and

unsorted. At the beginning, the sorted zone consists of one element. On each step, the algorithms expand it by one element inserting the first element from the unsorted zone in proper place in the sorted zone and shifting all larger elements one slot down.

Algorithm:

Insertion(Array A)Begin for i = 1 to length[A] do

Begin

Page 8: Final DAA Lab Manual

8

value := A[i];j := i – 1; while j>0 && A[j] > value do

Begin A[j+1] := A[j]; A[j] := value; j := j-1;

end;end;

end;

CODE:

#include<stdio.h>#include<conio.h>void main(){

int A[20],N,Temp,i,j;clrscr();printf("\n--------------------------------------------------------");printf("\n\n PROGRAM TO SORT THE NUMBERS USING BUBBLE SORT ");printf("\n\n--------------------------------------------------------");printf("\n\n\t ENTER THE NUMBER OF TERMS...: ");scanf("%d",&N);printf("\n\t ENTER THE ELEMENTS OF THE ARRAY...:");for(i=1; i<=N; i++){

gotoxy(25,11+i);scanf("\n\t\t%d",&A[i]);

}

for(i=1; i<=N-1; i++)for(j=1; j<=N-i;j++)

if(A[j]>A[j+1]){

Temp = A[j];A[j] = A[j+1];A[j+1] = Temp;

}printf("\n\tTHE ASCENDING ORDER LIST IS...:\n");for(i=1; i<=N; i++)

printf("\n\t\t\t%d",A[i]);printf("\n\n----------------------------------------------------------");

Page 9: Final DAA Lab Manual

9

getch();}

INPUT & OUTPUT:

--------------------------------------------------------

PROGRAM TO SORT THE NUMBERS USING INSERTION SORT

--------------------------------------------------------

ENTER THE NUMBER OF TERMS...: 5

ENTER THE ELEMENTS OF THE ARRAY...:

89 45 10 2 789

THE ASCENDING ORDER LIST IS...:

2 10 45 89 789

----------------------------------------------------------

Page 10: Final DAA Lab Manual

10

Program 4: To implement the Program of Bubble sort in C.

Object:

Write a program for arranging elements in ascending order using Bubble Sort Algorithm in ‘C’ language

Theory:

Bubble Sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted, comparing two items at a time and swapping them if they are in wrong order.

The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.

The algorithm gets its name from the way smaller elements “Bubble” to the top of the list. Because, it only uses comparisons to operate on elements, it is a comparison sort.

Time Complexity: Worst Case = O(n2) n = no. of items being sorted. Average Case = O(n2) Best Case = O(n2)

Algorithm:

Function Bubble_Sort (A: list[1…n]){

var int i, j;for i=n down to 1{

for j=1 to i-1{

if A[j] > A[j+1]swap(A, i, j)

}}

}

Page 11: Final DAA Lab Manual

11

CODE:

#include<stdio.h>#include<conio.h>void main(){

int A[20],N,Temp,i,j;clrscr();printf("\n--------------------------------------------------------");printf("\n\n PROGRAM TO SORT THE NUMBERS USING INSERTION SORT ");printf("\n\n--------------------------------------------------------");printf("\n\n\t ENTER THE NUMBER OF TERMS...: ");scanf("%d",&N);printf("\n\t ENTER THE ELEMENTS OF THE ARRAY...:");for(i=1; i<=N; i++){

gotoxy(25,11+i);scanf("\n\t\t%d",&A[i]);

}

for(i=2; i<=N; i++){

Temp = A[i];j = i-1;while(Temp<A[j] && j>=1){

A[j+1] = A[j];j = j-1;

}A[j+1] = Temp;

}printf("\n\tTHE ASCENDING ORDER LIST IS...:\n");for(i=1; i<=N; i++)

printf("\n\t\t\t%d",A[i]);printf("\n\n----------------------------------------------------------");getch();

}

Page 12: Final DAA Lab Manual

12

INPUT & OUTPUT:--------------------------------------------------------

PROGRAM TO SORT THE NUMBERS USING BUBBLE SORT

--------------------------------------------------------

ENTER THE NUMBER OF TERMS...: 5

ENTER THE ELEMENTS OF THE ARRAY...:

789 145 25 10 89

THE ASCENDING ORDER LIST IS...:

10 25 89 145 789

----------------------------------------------------------

Page 13: Final DAA Lab Manual

13

Program 5: To implement the Program of Merge Sort in C.

Object:-

Write a program for arranging elements in ascending order using Merge Sort Algorithm in ‘C’ language.

Theory:-

It follows the “Divide and Conquer” sratergy. It operates as follows:

Divide: Divide the n element sequence to be sorted into two subsequences of n/2 elements each.Conquer: Sort the two subsequences recursively using Merge Sort.Combine: Merge the two sorted subsequences to produce the sorted answer.

Time Complexity :Worst Case = Θ(n log n)Average Case = Θ(n log n)Best Case = Θ(n log n)

Algorithm:

Page 14: Final DAA Lab Manual

14

CODE:#include<stdio.h>#include<conio.h>#define MAX 20int array[MAX];main(){

int i,n;clrscr();printf("Enter the number of elements : ");scanf("%d",&n);for(i=0;i<n;i++){

printf("Enter element %d : ",i+1);scanf("%d",&array[i]);

}

printf("Unsorted list is :\n");for( i = 0 ; i<n ; i++)

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

merge_sort( 0, n-1);

printf("\nSorted list is :\n");for( i = 0 ; i<n ; i++)

printf("%d ", array[i]);printf("\n");getch();

}/*End of main()*/

merge_sort( int low, int high ){

int mid;if( low != high ){

mid = (low+high)/2;

Page 15: Final DAA Lab Manual

15

merge_sort( low , mid );merge_sort( mid+1, high );merge( low, mid, high );

}}/*End of merge_sort*/

merge( int low, int mid, int high ){

int temp[MAX];int i = low;int j = mid +1 ;int k = low ;

while( (i <= mid) && (j <=high) ){

if(array[i] <= array[j])temp[k++] = array[i++] ;

elsetemp[k++] = array[j++] ;

}/*End of while*/while( i <= mid )

temp[k++]=array[i++];while( j <= high )

temp[k++]=array[j++];

for(i= low; i <= high ; i++)array[i]=temp[i];

}

INPUT & OUTPUT:

Enter the number of elements : 8Enter element 1 : 78Enter element 2 : 12Enter element 3 : 4Enter element 4 : 56Enter element 5 : 789Enter element 6 : 1Enter element 7 : 45Enter element 8 : 6Unsorted list is :78 12 4 56 789 1 45 6Sorted list is :1 4 6 12 45 56 78 789

Page 16: Final DAA Lab Manual

16

Program 6: To implement the Program of Quick sort in C.

Object:-

Write a program for arranging elements in ascending order using Quick Sort Algorithm in ‘C’ language.

Theory:

Quick Sort is a list based on the “Divide and Conquer” strategy. In Quick Sort algorithm, we divide the list into two sublists, sort these sublists and recursively until the list is sorted.

The basic steps of Quick Sort Algorithm are as follows:- Choose a key element in the list which is called a pivot. Reorder the list with the rule that all elements which are less than the pivot

come before the pivot and so that all elements greater than the pivot come after it. After the partitioning, the pivot is in its final position.

Recursively, reorder two sublists; the sublists of lesser elements and the sublists of greater elements.

Time Complexity :Worst Case = Θ(n2)Average Case = Θ(n log n)Best Case = Θ(n log n)

Algorithm:

Page 17: Final DAA Lab Manual

17

CODE:#include<stdio.h>#include<conio.h>#define MAX 30enum bool { FALSE,TRUE };main(){

int array[MAX],n,i; clrscr();

printf("Enter the number of elements : ");scanf("%d",&n);

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

printf("Enter element %d : ",i+1);scanf("%d",&array[i]);

}

printf("Unsorted list is :\n");display(array,0,n-1);printf("\n");

quick(array,0,n-1);

printf("Sorted list is :\n");display(array,0,n-1);printf("\n");getch();

}/*End of main() */

quick(int arr[],int low,int up){

int piv,temp,left,right;

Page 18: Final DAA Lab Manual

18

enum bool pivot_placed=FALSE;left=low;right=up;piv=low; /*Take the first element of sublist as piv */

if(low>=up)return;

printf("Sublist : ");display(arr,low,up);

/*Loop till pivot is placed at proper place in the sublist*/while(pivot_placed==FALSE){

/*Compare from right to left */while( arr[piv]<=arr[right] && piv!=right )

right=right-1;if( piv==right ) pivot_placed=TRUE;if( arr[piv] > arr[right] ){

temp=arr[piv];arr[piv]=arr[right];arr[right]=temp;piv=right;

}/*Compare from left to right */while( arr[piv]>=arr[left] && left!=piv )

left=left+1;if(piv==left)

pivot_placed=TRUE;if( arr[piv] < arr[left] ){

temp=arr[piv];arr[piv]=arr[left];arr[left]=temp;piv=left;

}}/*End of while */printf("-> Pivot Placed is %d -> ",arr[piv]);display(arr,low,up);printf("\n");

quick(arr,low,piv-1);quick(arr,piv+1,up);

Page 19: Final DAA Lab Manual

19

}/*End of quick()*/display(int arr[],int low,int up){

int i;for(i=low;i<=up;i++)

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

INPUT & OUTPUT:

Enter the number of elements : 5Enter element 1 : 78Enter element 2 : 12Enter element 3 : 456Enter element 4 : 59Enter element 5 : 36Unsorted list is :78 12 456 59 36Sublist : 78 12 456 59 36 -> Pivot Placed is 78 -> 36 12 59 78 456Sublist : 36 12 59 -> Pivot Placed is 36 -> 12 36 59Sorted list is :12 36 59 78 456

Page 20: Final DAA Lab Manual

20

Program 7: To implement the Program of Merging two sorted array into a single array using C.

#include<stdio.h>#include<conio.h>

main(){

int arr1[20],arr2[20],arr3[40];int i,j,k;int max1,max2;clrscr();printf("Enter the number of elements in list1 : ");scanf("%d",&max1);printf("Take the elements in sorted order :\n");for(i=0;i<max1;i++){

printf("Enter element %d : ",i+1);scanf("%d",&arr1[i]);

}printf("Enter the number of elements in list2 : ");scanf("%d",&max2);printf("Take the elements in sorted order :\n");for(i=0;i<max2;i++){

printf("Enter element %d : ",i+1);scanf("%d",&arr2[i]);

}/* Merging */i=0; /*Index for first array*/j=0; /*Index for second array*/k=0; /*Index for merged array*/

Page 21: Final DAA Lab Manual

21

while( (i < max1) && (j < max2) ){

if( arr1[i] < arr2[j] )arr3[k++]=arr1[i++];

elsearr3[k++]=arr2[j++];

}/*End of while*//*Put remaining elements of arr1 into arr3*/while( i < max1 )

arr3[k++]=arr1[i++];/*Put remaining elements of arr2 into arr3*/while( j < max2 )

arr3[k++]=arr2[j++];

/*Merging completed*/printf("List 1 : ");for(i=0;i<max1;i++)

printf("%d ",arr1[i]);printf("\nList 2 : ");for(i=0;i<max2;i++)

printf("%d ",arr2[i]);printf("\nMerged list : ");for(i=0;i<max1+max2;i++)

printf("%d ",arr3[i]);printf("\n");getch();

}

INPUT & OUTPUT:

Enter the number of elements in list1 : 5Take the elements in sorted order :Enter element 1 : 2Enter element 2 : 4Enter element 3 : 6Enter element 4 : 8Enter element 5 : 10Enter the number of elements in list2 : 5Take the elements in sorted order :Enter element 1 : 1Enter element 2 : 3Enter element 3 : 5

Page 22: Final DAA Lab Manual

22

Enter element 4 : 7Enter element 5 : 9List 1 : 2 4 6 8 10List 2 : 1 3 5 7 9Merged list : 1 2 3 4 5 6 7 8 9 10

Program 8: To implement the Program of Radix Sort in C.

Objective: Write a program for arranging elements in ascending order using Radix Sort

Algorithm in ‘C’ language

Theory: Radix sort is a sorting algorithm that sorts integers by processing individual digits, by comparing individual digits sharing the same significant position. A positional notation is required, but because integers can represent strings of characters (e.g., names or dates) and specially formatted floating point numbers, radix sort is not limited to integers.

CODE:

# include<stdio.h>#include<conio.h># include<malloc.h>

struct node{

int info ;struct node *link;

}*start=NULL;

main(){

struct node *tmp,*q;int i,n,item;

printf("Enter the number of elements in the list : ");scanf("%d", &n);

Page 23: Final DAA Lab Manual

23

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

printf("Enter element %d : ",i+1);scanf("%d",&item);

/* Inserting elements in the linked list */tmp= malloc(sizeof(struct node));tmp->info=item;tmp->link=NULL;

if(start==NULL) /* Inserting first element */start=tmp;

else{

q=start;while(q->link!=NULL)

q=q->link;q->link=tmp;

}}/*End of for*/

printf("Unsorted list is :\n");display();radix_sort();printf("Sorted list is :\n");display ();getch();

}/*End of main()*/

display(){

struct node *p=start;while( p !=NULL){

printf("%d ", p->info);p= p->link;

}printf("\n");

}/*End of display()*/

radix_sort(){

int i,k,dig,maxdig,mindig,least_sig,most_sig;

Page 24: Final DAA Lab Manual

24

struct node *p, *rear[10], *front[10];

least_sig=1;most_sig=large_dig(start);

for(k = least_sig; k <= most_sig ; k++){

printf("PASS %d : Examining %dth digit from right ",k,k);for(i = 0 ; i <= 9 ; i++){

rear[i] = NULL;front[i] = NULL ;

}maxdig=0;mindig=9;p = start ;while( p != NULL){

/*Find kth digit in the number*/dig = digit(p->info, k);if(dig>maxdig)

maxdig=dig;if(dig<mindig)

mindig=dig;

/*Add the number to queue of dig*/if(front[dig] == NULL)

front[dig] = p ;else

rear[dig]->link = p ;rear[dig] = p ;p=p->link;/*Go to next number in the list*/

}/*End while *//* maxdig and mindig are the maximum amd minimum digits of the kth digits of all the numbers*/printf("mindig=%d maxdig=%d\n",mindig,maxdig);/*Join all the queues to form the new linked list*/start=front[mindig];for(i=mindig;i<maxdig;i++){

if(rear[i+1]!=NULL)rear[i]->link=front[i+1];

elserear[i+1]=rear[i];

Page 25: Final DAA Lab Manual

25

}rear[maxdig]->link=NULL;printf("New list : ");display();

}/* End for */

}/*End of radix_sort*/

/* This function finds number of digits in the largest element of the list */int large_dig(){

struct node *p=start ;int large = 0,ndig = 0 ;

while(p != NULL){

if(p ->info > large)large = p->info;

p = p->link ;}printf("Largest Element is %d , ",large);while(large != 0){

ndig++;large = large/10 ;

}

printf("Number of digits in it are %d\n",ndig);return(ndig);

} /*End of large_dig()*/

/*This function returns kth digit of a number*/int digit(int number, int k){

int digit, i ;for(i = 1 ; i <=k ; i++){

digit = number % 10 ;number = number /10 ;

}return(digit);

}/*End of digit()*/

INPUT & OUTPUT:

Page 26: Final DAA Lab Manual

26

Enter the number of elements in the list : 5Enter element 1 : 489Enter element 2 : 568Enter element 3 : 123Enter element 4 : 487Enter element 5 : 148Unsorted list is :489 568 123 487 148Largest Element is 568 , Number of digits in it are 3PASS 1 : Examining 1th digit from right mindig=3 maxdig=9New list : 123 487 568 148 489

PASS 2 : Examining 2th digit from right mindig=2 maxdig=8New list : 123 148 568 487 489

PASS 3 : Examining 3th digit from right mindig=1 maxdig=5New list : 123 148 487 489 568Sorted list is :123 148 487 489 568

Page 27: Final DAA Lab Manual

27

Program 9: To implement the Program of Selection Sort in C.

Objective: Write a program for arranging elements in ascending order using selection Sort

Algorithm in ‘C’ language

Theory: Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and also has performance advantages over more complicated algorithms in certain situations.

Algorithm:

The algorithm works as follows:

1. Find the minimum value in the list2. Swap it with the value in the first position3. Repeat the steps above for the remainder of the list (starting at the second position and

advancing each time)

Effectively, the list is divided into two parts: the sublist of items already sorted, which is built up from left to right and is found at the beginning, and the sublist of items remaining to be sorted, occupying the remainder of the array.

Mathematical definition

Let L be a non-empty set and such that f(L) = L' where:

1. L' is a permutation of L,

2. for all and ,

Page 28: Final DAA Lab Manual

28

3. ,

4. s is the smallest element of L, and

5. Ls is the set of elements of L without one instance of the smallest element of L.

CODE:#include <stdio.h>#include<conio.h>#define MAX 20

main(){

int arr[MAX], i,j,k,n,temp,smallest;printf("Enter the number of elements : ");scanf("%d",&n);for (i = 0; i < n; i++){

printf("Enter element %d : ",i+1);scanf("%d", &arr[i]);

}printf("Unsorted list is : \n");for (i = 0; i < n; i++)

printf("%d ", arr[i]);printf("\n");/*Selection sort*/for(i = 0; i< n - 1 ; i++){

/*Find the smallest element*/smallest = i;for(k = i + 1; k < n ; k++){

if(arr[smallest] > arr[k])smallest = k ;

}if( i != smallest ){

temp = arr [i];arr[i] = arr[smallest];arr[smallest] = temp ;

}printf("After Pass %d elements are : ",i+1);

Page 29: Final DAA Lab Manual

29

for (j = 0; j < n; j++)printf("%d ", arr[j]);

printf("\n");}/*End of for*/printf("Sorted list is : \n");for (i = 0; i < n; i++)

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

}

INPUT & OUTPUT:

Enter the number of elements : 5Enter element 1 : 78Enter element 2 : 59Enter element 3 : 15Enter element 4 : 12Enter element 5 : 2Unsorted list is :78 59 15 12 2After Pass 1 elements are : 2 59 15 12 78After Pass 2 elements are : 2 12 15 59 78After Pass 3 elements are : 2 12 15 59 78After Pass 4 elements are : 2 12 15 59 78Sorted list is :2 12 15 59 78

Page 30: Final DAA Lab Manual

30

Program 10: To implement the Program of Binary Search Tree with creation, insertion & Deletion operation in C.

Objective: Write a Program of Binary Search Tree in which insertion, Deletion & Preorder, Inorder & Postorder Traversal operation is performed in C language.

Theory:A graph data structure consists mainly of a finite (and possibly mutable) set of ordered pairs, called edges or arcs, of certain entities called nodes or vertices. As in mathematics, an edge (x,y) is said to point or go from x to y. The nodes may be part of the graph structure, or may be external entities represented by integer indices or references.

CODE:

# include <stdio.h># include <malloc.h>

struct node{

int info;struct node *lchild;struct node *rchild;

}*root;

main(){

int choice,num;root=NULL;

Page 31: Final DAA Lab Manual

31

while(1){

printf("\n");printf("1.Insert\n");printf("2.Delete\n");printf("3.Inorder Traversal\n");printf("4.Preorder Traversal\n");printf("5.Postorder Traversal\n");printf("6.Display\n");printf("7.Quit\n");printf("Enter your choice : ");scanf("%d",&choice);

switch(choice){ case 1:

printf("Enter the number to be inserted : ");scanf("%d",&num);insert(num);break;

case 2:printf("Enter the number to be deleted : ");scanf("%d",&num);del(num);break;

case 3:inorder(root);break;

case 4:preorder(root);break;

case 5:postorder(root);break;

case 6:display(root,1);break;

case 7:exit();

default:printf("Wrong choice\n");

}/*End of switch */}/*End of while */

}/*End of main()*/

Page 32: Final DAA Lab Manual

32

find(int item,struct node **par,struct node **loc){

struct node *ptr,*ptrsave;

if(root==NULL) /*tree empty*/{

*loc=NULL;*par=NULL;return;

}if(item==root->info) /*item is at root*/{

*loc=root;*par=NULL;return;

}/*Initialize ptr and ptrsave*/if(item<root->info)

ptr=root->lchild;else

ptr=root->rchild;ptrsave=root;

while(ptr!=NULL){

if(item==ptr->info){ *loc=ptr;

*par=ptrsave;return;

}ptrsave=ptr;if(item<ptr->info)

ptr=ptr->lchild;else

ptr=ptr->rchild; }/*End of while */ *loc=NULL; /*item not found*/ *par=ptrsave;

}/*End of find()*/

insert(int item){ struct node *tmp,*parent,*location;

find(item,&parent,&location);

Page 33: Final DAA Lab Manual

33

if(location!=NULL){

printf("Item already present");return;

}

tmp=(struct node *)malloc(sizeof(struct node));tmp->info=item;tmp->lchild=NULL;tmp->rchild=NULL;

if(parent==NULL)root=tmp;

elseif(item<parent->info)

parent->lchild=tmp;else

parent->rchild=tmp;}/*End of insert()*/

del(int item){

struct node *parent,*location;if(root==NULL){

printf("Tree empty");return;

}

find(item,&parent,&location);if(location==NULL){

printf("Item not present in tree");return;

}

if(location->lchild==NULL && location->rchild==NULL)case_a(parent,location);

if(location->lchild!=NULL && location->rchild==NULL)case_b(parent,location);

if(location->lchild==NULL && location->rchild!=NULL)case_b(parent,location);

if(location->lchild!=NULL && location->rchild!=NULL)case_c(parent,location);

Page 34: Final DAA Lab Manual

34

free(location);}/*End of del()*/

case_a(struct node *par,struct node *loc ){

if(par==NULL) /*item to be deleted is root node*/root=NULL;

elseif(loc==par->lchild)

par->lchild=NULL;else

par->rchild=NULL;}/*End of case_a()*/

case_b(struct node *par,struct node *loc){

struct node *child;

/*Initialize child*/if(loc->lchild!=NULL) /*item to be deleted has lchild */

child=loc->lchild;else /*item to be deleted has rchild */

child=loc->rchild;

if(par==NULL ) /*Item to be deleted is root node*/root=child;

elseif( loc==par->lchild) /*item is lchild of its parent*/

par->lchild=child;else /*item is rchild of its parent*/

par->rchild=child;}/*End of case_b()*/

case_c(struct node *par,struct node *loc){

struct node *ptr,*ptrsave,*suc,*parsuc;

/*Find inorder successor and its parent*/ptrsave=loc;ptr=loc->rchild;while(ptr->lchild!=NULL){

ptrsave=ptr;ptr=ptr->lchild;

Page 35: Final DAA Lab Manual

35

}suc=ptr;parsuc=ptrsave;

if(suc->lchild==NULL && suc->rchild==NULL)case_a(parsuc,suc);

elsecase_b(parsuc,suc);

if(par==NULL) /*if item to be deleted is root node */root=suc;

elseif(loc==par->lchild)

par->lchild=suc;else

par->rchild=suc;

suc->lchild=loc->lchild;suc->rchild=loc->rchild;

}/*End of case_c()*/

preorder(struct node *ptr){

if(root==NULL){

printf("Tree is empty");return;

}if(ptr!=NULL){

printf("%d ",ptr->info);preorder(ptr->lchild);preorder(ptr->rchild);

}}/*End of preorder()*/

inorder(struct node *ptr){

if(root==NULL){

printf("Tree is empty");return;

}if(ptr!=NULL)

Page 36: Final DAA Lab Manual

36

{inorder(ptr->lchild);printf("%d ",ptr->info);inorder(ptr->rchild);

}}/*End of inorder()*/

postorder(struct node *ptr){

if(root==NULL){

printf("Tree is empty");return;

}if(ptr!=NULL){

postorder(ptr->lchild);postorder(ptr->rchild);printf("%d ",ptr->info);

}}/*End of postorder()*/display(struct node *ptr,int level){

int i;if ( ptr!=NULL ){

display(ptr->rchild, level+1);printf("\n");for (i = 0; i < level; i++)

printf(" ");printf("%d", ptr->info);display(ptr->lchild, level+1);

}/*End of if*/}/*End of display()*/

INPUT & OUTPUT:1.Insert2.Delete3.Inorder Traversal4.Preorder Traversal5.Postorder Traversal6.Display7.QuitEnter your choice : 1

Page 37: Final DAA Lab Manual

37

Enter the number to be inserted : 451.Insert2.Delete3.Inorder Traversal4.Preorder Traversal5.Postorder Traversal6.Display7.QuitEnter your choice : 1Enter the number to be inserted : 781.Insert2.Delete3.Inorder Traversal4.Preorder Traversal5.Postorder Traversal6.Display7.QuitEnter your choice : 1Enter the number to be inserted : 891.Insert2.Delete3.Inorder Traversal4.Preorder Traversal5.Postorder Traversal6.Display7.QuitEnter your choice : 1Enter the number to be inserted : 45Item already present1.Insert2.Delete3.Inorder Traversal4.Preorder Traversal5.Postorder Traversal6.Display7.QuitEnter your choice : 6

89 78 451.Insert2.Delete3.Inorder Traversal4.Preorder Traversal

Page 38: Final DAA Lab Manual

38

5.Postorder Traversal6.Display7.QuitEnter your choice : 345 78 891.Insert2.Delete3.Inorder Traversal4.Preorder Traversal5.Postorder Traversal6.Display7.QuitEnter your choice : 589 78 45