Sie sind auf Seite 1von 56

Q1)Write a program to sort the array element using

1) Merge Sort
2) Bubble Sort
3) Insertion Sort
4) Selection Sort
Draw the line graph for time complexity.

BUBBLE SORT

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
using namespace std;
/*Author-Ajay Raj Srivastava 141164
Bubble Sort O(n2)*/
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
for (j = 0; j < n-i-1; j++) //Last i elements are already in place
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
int main()
{
clock_t start,end;
int n;
cout<<"Enter size of array"<<endl;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
a[i]=rand()%n;
cout<<"Before Bubble Sort:-"<<endl;

//
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
start=clock();
bubbleSort(a,n);
end=clock();
cout<<"After Bubble Sort:-"<<endl;
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
float diff ((float)end-(float)start);
float seconds = diff / CLOCKS_PER_SEC;
printf("\nTime taken %f",seconds); //CLK_TCK
return 0;
}
MERGE SORT
//Author- Ajay Raj Srivastava 141164
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
// Function to Merge Arrays L and R into A.
// lefCount = number of elements in L
// rightCount = number of elements in R.
void Merge(int *A,int *L,int leftCount,int *R,int rightCount) {
int i,j,k;
// i - to mark the index of left aubarray (L)
// j - to mark the index of right sub-raay (R)
// k - to mark the index of merged subarray (A)
i = 0; j = 0; k =0;
while(i<leftCount && j< rightCount) {
if(L[i] < R[j]) A[k++] = L[i++];
else A[k++] = R[j++];
}
while(i < leftCount) A[k++] = L[i++];
while(j < rightCount) A[k++] = R[j++];
}

// Recursive function to sort an array of integers.


void MergeSort(int *A,int n) {
int mid,i, *L, *R;
if(n < 2) return; // base condition. If the array has less than two element, do nothing.
mid = n/2; // find the mid index.
// create left and right subarrays
// mid elements (from index 0 till mid-1) should be part of left sub-array
// and (n-mid) elements (from mid to n-1) will be part of right sub-array
L = (int*)malloc(mid*sizeof(int));
R = (int*)malloc((n- mid)*sizeof(int));
for(i = 0;i<mid;i++) L[i] = A[i]; // creating left subarray
for(i = mid;i<n;i++) R[i-mid] = A[i]; // creating right subarray
MergeSort(L,mid); // sorting the left subarray
MergeSort(R,n-mid); // sorting the right subarray
Merge(A,L,mid,R,n-mid); // Merging L and R into A as sorted list.
free(L);
free(R);
}
int main()
{
clock_t start,end;
int n;
cout<<"Enter size of array"<<endl;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
a[i]=rand()%n;
cout<<"Before Merge Sort:-"<<endl;
//
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
start=clock();
MergeSort(a,n);
end=clock();
cout<<"After Merge Sort:-"<<endl;
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;

float diff ((float)end-(float)start);


float seconds = diff / CLOCKS_PER_SEC;
printf("\nTime taken %f",seconds);//CLK_TCK
return 0;
}

SELECTION SORT
//Author-Ajay Raj Srivastava 141164
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
using namespace std;
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]);
}
}
int main()
{
clock_t start,end;
int n;
cout<<"Enter size of array"<<endl;
cin>>n;
int a[n];

for(int i=0;i<n;i++)
a[i]=rand()%n;
cout<<"Before Selection Sort:-"<<endl;
//
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
start=clock();
selectionSort(a,n);
end=clock();
cout<<"After Selection Sort:-"<<endl;
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
float diff ((float)end-(float)start);
float seconds = diff / CLOCKS_PER_SEC;
printf("\nTime taken %f",seconds);//CLK_TCK
return 0;
}

INSERTION SORT
//Author-Ajay Raj Srivastava
#include<iostream>
#include<stdlib.h>
#include<time.h>
#include<stdio.h>
using namespace std;
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;
}
}
int main()
{
clock_t start,end;
int n;
cout<<"Enter size of array"<<endl;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
a[i]=rand()%n;
cout<<"Before Insertion Sort:-"<<endl;
//
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
start=clock();
insertionSort(a,n);
end=clock();
cout<<"After Insertion Sort:-"<<endl;
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
float diff ((float)end-(float)start);
float seconds = diff / CLOCKS_PER_SEC;
printf("\nTime taken %f",seconds);//CLK_TCK
return 0;
}

Q2)Write a program to sort the array element using


1) Counting Sort
2) Bucket Sort
COUNT SORT
//Author-Ajay Raj Srivastava 141164
#include<iostream>
using namespace std;
int main()
{
int n,max=-1;//size
cout<<"Enter size of array"<<endl;
cin>>n;
int a[n],b[n+1];
cout<<"Enter elements for array"<<endl;
for(int i=0;i<n;i++)
{ cin>>a[i];
if(a[i]>max)
max=a[i];//range-K
}
//counting sort
int c[max+1];
for(int i=0;i<max+1;i++)
c[i]=0;
for(int i=0;i<n;i++)
c[a[i]]++;
for(int i=1;i<max+1;i++)
c[i]+=c[i-1];
for(int i=n-1;i>=0;i--)
{b[c[a[i]]]=a[i];
c[a[i]]--;}
//sorted array
cout<<"Sorted array is"<<endl;
for(int i=1;i<n+1;i++)
cout<<b[i]<<" ";
cout<<endl;
}
BUCKET SORT
//Author-Ajay Raj Srivastava 141164
#include<iostream>
#include<math.h>

#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int n;
cout<<"Enter size of array"<<endl;
cin>>n;
float a[n+1];
cout<<"Enter elements for arrays"<<endl;
for(int i=1;i<n+1;i++)
cin>>a[i];
vector< vector<float> >v(n);//vector of vector<int> of size n;
for(int i=1;i<n+1;i++)
v[floor(n*a[i])].push_back(a[i]);
for (int i=0; i<n; i++)
sort(v[i].begin(),v[i].end());
int index = 1;
for (int i = 0; i < n; i++)
for (int j = 0; j < v[i].size(); j++)
a[index++] = v[i][j];
for(int i=1;i<n+1;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}
Q2-1. Given an array S of unsorted elements. Design an
algorithm and implement that to find a pair x, y such
that xy from S that minimizes |x-y|. The worst case
running time of the algorithm should be O (nlgn).
//Author-Ajay Raj Srivastava 141164
#include<iostream>
#include<time.h>
#include<set>
#include<stdlib.h>
#include<vector>
using namespace std;
void Merge(int *A,int *L,int leftCount,int *R,int rightCount) {
int i,j,k;

i = 0; j = 0; k =0;
while(i<leftCount && j< rightCount) {
if(L[i] < R[j]) A[k++] = L[i++];
else A[k++] = R[j++];
}
while(i < leftCount) A[k++] = L[i++];
while(j < rightCount) A[k++] = R[j++];
}
// Recursive function to sort an array of integers.
void MergeSort(int *A,int n) {
int mid,i, *L, *R;
if(n < 2) return; // base condition
mid = n/2;
L = (int*)malloc(mid*sizeof(int));
R = (int*)malloc((n- mid)*sizeof(int));
for(i = 0;i<mid;i++) L[i] = A[i];
for(i = mid;i<n;i++) R[i-mid] = A[i];
MergeSort(L,mid);
MergeSort(R,n-mid);
Merge(A,L,mid,R,n-mid);
free(L);
free(R);
}
int main()
{
int n;
cout<<"Enter size of array"<<endl;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
a[i]=rand()%n;//generates random number can be same also
cout<<"Randomnly generated array"<<endl;
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl<<endl;
MergeSort(a,n);

vector<int>diff;

for(int i=1;i<n-1;i++)
{
if(a[i]!=a[i-1])
diff.push_back(a[i]-a[i-1]); //calculating difference
}
int min=10000000;
for(int i=0;i<diff.size();i++) //min difference
{if(diff[i]<=min)
min=diff[i];
}
for(int i=1;i<n-1;i++)
{
if(a[i]!=a[i-1] && a[i]-a[i-1]==min)
{cout<<"pairs are "<<a[i]<<" and "<<a[i-1]<<endl;
break;}
}
system("pause");
diff.clear();
return 0;
}
Q2-2). Given two arrays A 1 , A 2 of size n and a number x,
design an algorithm to find whether there exists a pair
of elements one from A 1 and other from A 2 whose sum
is equal to x. Also find the indices of those elements.
//Author-Ajay Raj Srivastava 141164
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
cout<<"Enter sizes of arrays" <<endl;
int n;
cin>>n;
int a1[n],a2[n];
cout<<"Enter data for array 1"<<endl;
for(int i=0;i<n;i++)
cin>>a1[i];
cout<<"Enter data for array 2"<<endl;

for(int i=0;i<n;i++)
cin>>a2[i];
int x;
cout<<"Enter value of x"<<endl;
cin>>x;
int flag=-1;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(a1[i]+a2[j]==x)
{ flag=1;
cout<<"Yes,with i1="<<i<<"and i2="<<j<<endl;}
}
}
if(flag==-1)
cout<<"No"<<endl;
system("pause");
return 0;
}
Q2-3. Develop an algorithm to solve the maximum
segment sum problem.
#include<iostream>
using namespace std;
int main()
{
//Author-Ajay Raj Srivastava 141164
//Kadane's Algorithm used for maximum segment sum
int max_so_far=0,max_ending_here=0;
int n;
cout<<"Enter size of array"<<endl;
cin>>n;
int a[n];
cout<<"Enter elements for array"<<endl;
for(int i=0;i<n;i++)
cin>>a[i];
for(int i=0;i<n;i++)
{
max_ending_here+=a[i];
if(max_ending_here<0)
max_ending_here=0;
if(max_so_far<max_ending_here)

max_so_far=max_ending_here;
}
cout<<"Maximum segment sum "<<max_so_far<<endl;
return 0;
}
Q3-1)Build a Max-Heap Tree for any array. Analyze the
operation in terms of running time and find the time
complexity of the algorithm.
//Author-Ajay Raj Srivastava 141164
#include<iostream>
using namespace std;
void max_heapify(int* a,int i,int n)
{
int largest,temp;
int l=2*i;
int r=l+1;
if(l<=n && a[l]>a[i])
largest=l;
else
largest=i;
if(r<=n && a[r]>a[largest])
largest=r;
if(largest!=i)
{temp=a[i];
a[i]=a[largest];
a[largest]=temp;
max_heapify(a,largest,n);
}
}
int main()
{
int n,i;
cout<<"Enter size of array"<<endl;
cin>>n;
cout<<"Enter elements of array"<<endl;
int a[n+1];
for(i=1;i<n+1;i++ )
cin>>a[i];
cout<<"Max heapify:-"
for(i=n/2;i>=1;i--)
max_heapify(a,i,n);

for(i=1;i<n+1;i++ )
cout<<a[i]<<" ";
cout<<endl;
return 0;
}
Q3-2). Implement an algorithm to build a Min-Heap Tree
for any array. Analyze the operation in terms of
running time and find the time complexity of the
algorithm.
//Author-Ajay Raj Srivastava 141164x
#include<iostream>
using namespace std;
void min_heapify(int* a,int i,int n)
{
int smallest,temp;
int l=2*i;
int r=l+1;
if(l<=n && a[l]<a[i])
smallest=l;
else
smallest=i;
if(r<=n && a[r]<a[smallest])
smallest=r;
if(smallest!=i)
{temp=a[i];
a[i]=a[smallest];
a[smallest]=temp;
min_heapify(a,smallest,n);
}
}
int main()
{
int n,i;
cout<<"Enter size of array"<<endl;
cin>>n;
cout<<"Enter elements of array"<<endl;
int a[n+1];
for(i=1;i<n+1;i++ )
cin>>a[i];
cout<<"Min heapify:-"<<endl;
for(i=n/2;i>=1;i--)
min_heapify(a,i,n);
for(i=1;i<n+1;i++ )
cout<<a[i]<<" ";
cout<<endl;

return 0;
}
Q3-3)Q2. Design and implement an algorithm to find the Kth
largest elements of an unsorted array in O(n+klgn)
time.
//Author-Ajay Raj Srivastava 141164
#include<iostream>
using namespace std;
void max_heapify(int* a,int i,int n)
{
int largest,temp;
int l=2*i;
int r=l+1;
if(l<=n && a[l]>a[i])
largest=l;
else
largest=i;
if(r<=n && a[r]>a[largest])
largest=r;
if(largest!=i)
{temp=a[i];
a[i]=a[largest];
a[largest]=temp;
max_heapify(a,largest,n);
}
}
void build_heap(int* a,int n)
{
int i;
for(i=n/2;i>=1;i--)
max_heapify(a,i,n);
}
int extractkth(int* a,int k,int n)
{
int kth;
while(k--)
{kth=a[1];
a[1]=-1;
build_heap(a,n);
}
return kth;
}
int main()
{

int n,i,k;
cout<<"Enter size of array"<<endl;
cin>>n;
cout<<"Enter elements of array"<<endl;
int a[n+1];
for(i=1;i<n+1;i++ )
cin>>a[i];
build_heap(a,n);
cout<<"Enter k to find kth largest element in given unsorted array"<<endl;
cin>>k;
cout<<extractkth(a,k,n)<<endl;
return 0;
}

LAB EXERCISE-4
Implement an algorithm of Max-Priority-Queue for any array of elements having
INSERT, EXTRACT-MAX, INCREASE-KEY operations. Analyze its operations in
terms of running time and find the time complexity of the algorithm.
AlgorithmMAX-HEAP-INSERT(A, key, n)
1. heap-size[A] n + 1
2. A[n + 1] -
3. HEAP-INCREASE-KEY(A, n + 1, key)
HEAP-INCREASE-KEY(A, i, key)
1. if key < A[i]
2.
then error new key is smaller than current key
3. A[i] key
4. while i > 1 and A[PARENT(i)] < A[i]
5.
do exchange A[i] A[PARENT(i)]
6.
i PARENT(i)
HEAP-EXTRACT-MAX(A, n)
1. if n < 1
2.
then error heap underflow
3. max A[1]
4. A[1] A[n]
5. MAX-HEAPIFY(A, 1, n-1)
remakes heap
6. return max
MAX-HEAPIFY(A, i, n)
1. l LEFT(i)
2. r RIGHT(i)
3. if l n and A[l] > A[i]
4.
then largest l
5.
else largest i
6. if r n and A[r] > A[largest]
7.
then largest r
8. if largest i
9.
then exchange A[i] A[largest]
10.
MAX-HEAPIFY(A, largest, n)

Program#include<iostream>
#include<stdlib.h>
#include<math.h>
using namespace std;
int arr1[1000];
void input(int n)
{
int *a = arr1;
for(int i = 0; i < n; i++)
{
*(a+i) = rand();
}
}
int left(int i)
{
return (2*i)+1;
}
int right(int i)
{
return (2*i)+2;
}
int parent(int i)
{
return (i-1)/2;
}
void max_heapify(int *a, int i, int n)
{
int l, r, largest, temp;
l = left(i);

r = right(i);
if( ( l<n ) && ( *(a+l) > *(a+i) ) )
{
largest = l;
}
else
{
largest = i;
}
if( ( r<n ) && ( *(a+r) > *(a+largest) ))
{
largest = r;
}
if( largest != i )
{
temp = *(a+i);
*(a+i) = *(a+largest);
*(a+largest) = temp;
max_heapify(a, largest, n);
}
}
void display(int *a, int n)
{
for(int i = 0; i < n; i++)
{
cout<<(*(a+i))<<" ";
}
cout<<endl;
}
void build_max_heap(int *a, int n)
{
for(int i = floor((n-1)/2); i >= 0; i--)
{
max_heapify(a, i, n);
}
}
void heap_sort(int *a, int n)
{
int i, temp;
build_max_heap(a, n);
for (i = n-1; i > 0; i--)
{
temp = *a;
*a = *(a+i);
*(a+i) = temp;
max_heapify(a, 0, i);
}
}
int heap_maximum(int *a, int n)
{
if(n == 0)
{
return -1;
}
else
{
return *(a+0);
}
}
int heap_extract_max(int *a, int *n)
{
int max;
if(n==0)
{
return -1;
}
else
{
build_max_heap(a,*n);

max = *a;
*a = *(a+(*n)-1);
(*n)--;
max_heapify(a, 0, *n);
}
return max;
}
void heap_increase_key(int *a, int i, int key)
{
int temp;
i--;
if(key < *(a+i))
{
cout<<"\nNew key is smaller than current key";
goto x;
}
*(a+i) = key;
while(i>0 && *(a+parent(i)) < *(a+i))
{
temp = *(a+parent(i));
*(a+parent(i)) = *(a+i);
*(a+i) = temp;
i = parent(i) ;
}
x:
;
}
void max_heap_insert(int *a, int key, int *n)
{
(*n)++;
*(a+(*n)-1) = -1;
heap_increase_key(a,*n,key);
}
int main()
{
int *arr = arr1, size, choice, max, index, new_key;
do
{
cout<<"\n1. Create Heap\n2. Maximum Heapify\n3. Build Maximum Heap\n4. Heap Sort\n5. Heap
Extract Maximum\n6. Heap Maximum\n7. Heap Increase Key\n8. Maximum Heap Insert\n9. Exit\n";
cout<<"\nENter your choice : ";
cin>>choice;
switch(choice)
{
case 1 :
{
cout<<"\nEnter size of heap to create : ";
cin>>size;
input(size);
cout<<"\nHeap created.\n";
display(arr,size);
cout<<endl;
break;
}
case 2 :
{
cout<<"\nEnter index of element to perform Max Heapify on :";
cin>>index;
max_heapify(arr,index,size);
cout<<"\nAfter Maximum Heapify : ";
display(arr, size);
break;
}
case 3 :
{
build_max_heap(arr, size);
cout<<"\nAfter Build Maximum Heap : ";
display(arr, size);

break;
}
case 4 :
{
heap_sort(arr, size);
cout<<"\nAfter Heap Sort : ";
display(arr, size);
break;
}
case 5 :
{
max = heap_extract_max(arr, &size);
cout<<"\nMaximum element from heap : "<<max<<endl;
cout<<"After Heap Extract Maximum, new Heap : ";
display(arr, size);
break;
}
case 6 :
{
max = heap_maximum(arr, size);
cout<<"\nMaximum element from heap : "<<max<<endl;
break;
}
case 7 :
{
cout<<"\nEnter index of element to increse key : ";
cin>>index;
cout<<"Enter new value of key : ";
cin>>new_key;
heap_increase_key(arr, index, new_key);
cout<<"\nNew heap after changes : ";
display(arr, size);
break;
}
case 8 :
{
cout<<"\nEnter the value of new key to insert : ";
cin>>new_key;
max_heap_insert(arr, new_key, &size);
cout<<"\nNew heap after adding a new key : ";
display(arr, size);
break;
}
case 9 :
{
exit(0);
}
default :
{
cout<<"\nEnter valid choice : ";
break;
}
}
}while(choice != 9);
return 0;
}

Q1. Implement an algorithm of Min-Priority-Queue for any array of elements


having INSERT, EXTRACTMIN, DECREASE-KEY operations. Analyze its operations
in terms of running time and find the time complexity of the algorithm.
AlgorithmMIN-HEAP-INSERT(A, key, n)
1. heap-size[A] n + 1
2. A[n + 1] -
3. HEAP-DECREASE-KEY(A, n + 1, key)
HEAP-DECREASE-KEY(A, i, key)

1. if key >A[i]
2.
then error new key is larger than current key
3. A[i] key
4. while i > 1 and A[PARENT(i)] > A[i]
5.
do exchange A[i] A[PARENT(i)]
6.
i PARENT(i)
HEAP-EXTRACT-MIN(A, n)
1. if n < 1
2.
then error heap underflow
3. min A[s]
4. A[s] A[n]
5. MIN-HEAPIFY(A, 1, n-1)
remakes heap
6. return min
MIN_HEAPIFY(A,i)
{
l=LEFT(i)
r=RIGHT(i)
if((l<=A.heap_size)AND(A[l]<A[i]))
small=l
else
small=i
if((r<=A.heapsize)&&(A[small]>A[r]))
small=r
if(small!=i)
{
exchange A[i] with A[small]
MIN_HEAPIFY(A,i)
}
}

Program#include<iostream>
#include<stdlib.h>
#include<math.h>
using namespace std;
int arr1[1000];
void input(int n)
{
int *a = arr1;
for(int i = 0; i < n; i++)
{
*(a+i) = rand();
}
}
int left(int i)
{
return (2*i)+1;
}
int right(int i)
{
return (2*i)+2;
}
int parent(int i)
{
return (i-1)/2;
}
void min_heapify(int *a, int i, int n)
{
int l, r, smallest, temp;
l = left(i);
r = right(i);
if( ( l<n ) && ( *(a+l) < *(a+i) ) )
{
smallest = l;
}
else
{
smallest = i;

}
if( ( r<n ) && ( *(a+r) < *(a+smallest) ))
{
smallest = r;
}
if( smallest != i )
{
temp = *(a+i);
*(a+i) = *(a+smallest);
*(a+smallest) = temp;
min_heapify(a, smallest, n);
}
}
void build_min_heap(int *a, int n)
{
for(int i = floor((n-1)/2); i >= 0; i--)
{
min_heapify(a, i, n);
}
}
void heap_sort_min(int *a, int n)
{
int i, temp;
build_min_heap(a, n);
for (i = n-1; i > 0; i--)
{
temp = *a;
*a = *(a+i);
*(a+i) = temp;
min_heapify(a, 0, i);
}
}
void display(int *a, int n)
{
for(int i = 0; i < n; i++)
{
cout<<(*(a+i))<<" ";
}
cout<<endl;
}
int heap_minimum(int *a, int n)
{
if(n == 0)
{
return -1;
}
else
{
return *(a+0);
}
}
int heap_extract_min(int *a, int *n)
{
int min;
if(n==0)
{
return -1;
}
else
{
build_min_heap(a,*n);
min = *a;
*a = *(a+(*n)-1);
(*n)--;
min_heapify(a, 0, *n);
}
return min;
}
void heap_decrease_key(int *a, int i, int key)

{
int temp;
i--;
if(key > *(a+i))
{
cout<<"\nNew key is greater than current key";
goto x;
}
*(a+i) = key;
while(i>0 && *(a+parent(i)) > *(a+i))
{
temp = *(a+parent(i));
*(a+parent(i)) = *(a+i);
*(a+i) = temp;
i = parent(i) ;
}
x:
;
}
void min_heap_insert(int *a, int key, int *n)
{
(*n)++;
*(a+(*n)-1) = -1;
heap_decrease_key(a,*n,key);
}
int main()
{
int *arr = arr1, size, choice, min, index, new_key;
do
{
cout<<"\n1. Create Heap\n2. Minimum Heapify\n3. Build Minimum Heap\n4. Heap Sort\n5. Heap
Extract Minimum\n6. Heap Minimum\n7. Heap Decrease Key\n8. Minimum Heap Insert\n9. Exit\n";
cout<<"\nEnter your choice : ";
cin>>choice;
switch(choice)
{
case 1 :
{
cout<<"\nEnter size of heap to create : ";
cin>>size;
input(size);
cout<<"\nHeap created.\n";
display(arr,size);
cout<<endl;
break;
}
case 2 :
{
cout<<"\nEnter index of element to perform Min Heapify on :";
cin>>index;
min_heapify(arr,index,size);
cout<<"\nAfter Minimum Heapify : ";
display(arr, size);
break;
}
case 3 :
{
build_min_heap(arr, size);
cout<<"\nAfter Build Minimum Heap : ";
display(arr, size);
break;
}
case 4 :
{
heap_sort_min(arr, size);
cout<<"\nAfter Heap Sort : ";
display(arr, size);
break;

}
case 5 :
{
min = heap_extract_min(arr, &size);
cout<<"\nMinimum element from heap : "<<min<<endl;
cout<<"After Heap Extract Minimum, new Heap : ";
display(arr, size);
break;
}
case 6 :
{
min = heap_minimum(arr, size);
cout<<"\nMinimum element from heap : "<<min<<endl;
break;
}
case 7 :
{
cout<<"\nEnter index of element to decrease key : ";
cin>>index;
cout<<"Enter new value of key : ";
cin>>new_key;
heap_decrease_key(arr, index, new_key);
cout<<"\nNew heap after changes : ";
display(arr, size);
break;
}
case 8 :
{
cout<<"\nEnter the value of new key to insert : ";
cin>>new_key;
min_heap_insert(arr, new_key, &size);
cout<<"\nNew heap after adding a new key : ";
display(arr, size);
break;
}
case 9 :
{
exit(0);
}
default :
{
cout<<"\nEnter valid choice : ";
break;
}
}
}while(choice != 9);
return 0;
}

LAB EXERCISE-5
Write a menu driven program showing following operations in a binary search
tree through
1. Inorder Traversal
2. Preorder Traversal
3. Postorder Traversal
(A) Insertion
(B) Deletion
(C) Searching
Analyze the operation in terms of running time and find the time complexity of
the algorithm.
AlgorithmINORDER-TREE-WALK(x)
7. if x NIL
8.
then INORDER-TREE-WALK ( left [x] )
9.
print key [x]
10.
INORDER-TREE-WALK ( right [x] )
Preorder(root): Traverse a binary tree in node-left-right sequence.
7. If (root is not null)
8.
process (root)
9.
Preorder (leftSubtree)
10.
Preorder (rightSubtree)
Postorder(root): Traverse a binary tree in left-right-node sequence.
11.
If (root is not null)
12.
Postorder (leftSubtree)
13.
Postorder (rightSubtree)
14.
process (root)
TREE-SEARCH(x, k)
4. if x = NIL or k = key [x]
5.
then return x
6. if k < key [x]
7.
then return TREE-SEARCH(left [x], k )
else return
TREE-SEARCH(right [x], k )
TREE-INSERT(T, z)
7. y NIL
8. x root [T]
9. while x NIL
10.
do y x
11.
if key [z] < key [x]
12.
then x left [x]
13.
else x right [x]
14.
p[z] y
15.
if y = NIL
16.
then root [T] z
Tree T was empty
17.
else if key [z] < key [y]
18.
then left [y] z
else right [y] z
TREE-DELETE(T, z)
7. if left[z] = NIL or right[z] = NIL
8.
then y z

9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.

else y TREE-SUCCESSOR(z)
if left[y] NIL
then x left[y]
else x right[y]
if x NIL
then p[x] p[y]
if p[y] = NIL
then root[T] x
else if y = left[p[y]]
then left[p[y]] x
else right[p[y]] x
if y z
then key[z] key[y]
copy ys satellite data into z
return y

Program#include <stdio.h>
#include <stdlib.h>
struct btnode
{
int value;
struct btnode *l;
struct btnode *r;
}*root = NULL, *temp = NULL, *t2, *t1;
void delete1();
void insert();
void delete();
void inorder(struct btnode *t);
void create();
void search(struct btnode *t);
void preorder(struct btnode *t);
void postorder(struct btnode *t);
void search1(struct btnode *t,int data);
int flag = 1;
void main()
{
int ch;
printf("\nOPERATIONS ---");
printf("\n1 - Insert an element into tree\n");
printf("2 - Delete an element from the tree\n");
printf("3 - Inorder Traversal\n");
printf("4 - Preorder Traversal\n");
printf("5 - Postorder Traversal\n");
printf("6 - Exit\n");
while(1)
{
printf("\nEnter your choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
inorder(root);
break;
case 4:
preorder(root);
break;

case 5:
postorder(root);
break;
case 6:
exit(0);
default :
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}
/* To insert a node in the tree */
void insert()
{
create();
if (root == NULL)
root = temp;
else
search(root);
}
/* To create a node */
void create()
{
int data;
printf("Enter data of node to be inserted : ");
scanf("%d", &data);
temp = (struct btnode *)malloc(1*sizeof(struct btnode));
temp->value = data;
temp->l = temp->r = NULL;
}
/* Function to search the appropriate position to insert the new node */
void search(struct btnode *t)
{
if ((temp->value > t->value) && (t->r != NULL))
/* value more than root node value insert at right */
search(t->r);
else if ((temp->value > t->value) && (t->r == NULL))
t->r = temp;
else if ((temp->value < t->value) && (t->l != NULL)) /* value less than root node value insert at left */
search(t->l);
else if ((temp->value < t->value) && (t->l == NULL))
t->l = temp;
}
/* recursive function to perform inorder traversal of tree */
void inorder(struct btnode *t)
{
if (root == NULL)
{
printf("No elements in a tree to display");
return;
}
if (t->l != NULL)
inorder(t->l);
printf("%d -> ", t->value);
if (t->r != NULL)
inorder(t->r);
}
/* To check for the deleted node */
void delete()
{
int data;
if (root == NULL)
{
printf("No elements in a tree to delete");
return;
}
printf("Enter the data to be deleted : ");
scanf("%d", &data);
t1 = root;
t2 = root;

search1(root, data);
}
/* To find the preorder traversal */
void preorder(struct btnode *t)
{
if (root == NULL)
{
printf("No elements in a tree to display");
return;
}
printf("%d -> ", t->value);
if (t->l != NULL)
preorder(t->l);
if (t->r != NULL)
preorder(t->r);
}
/* To find the postorder traversal */
void postorder(struct btnode *t)
{
if (root == NULL)
{
printf("No elements in a tree to display ");
return;
}
if (t->l != NULL)
postorder(t->l);
if (t->r != NULL)
postorder(t->r);
printf("%d -> ", t->value);
}
void search1(struct btnode *t, int data)
{
if ((data>t->value))
{
t1 = t;
search1(t->r, data);
}
else if ((data < t->value))
{
t1 = t;
search1(t->l, data);
}
else if ((data==t->value))
{
delete1(t);
}
}
/* To delete a node */
void delete1(struct btnode *t)
{
int k;
/* To delete leaf node */
if ((t->l == NULL) && (t->r == NULL))
{
if (t1->l == t)
{
t1->l = NULL;
}
else
{
t1->r = NULL;
}
t = NULL;
free(t);
return;
}
/* To delete node having one left hand child */
else if ((t->r == NULL))

{
if (t1 == t)
{
root = t->l;
t1 = root;
}
else if (t1->l == t)
{
t1->l = t->l;
}
else
{
t1->r = t->l;
}
t = NULL;
free(t);
return;
}
/* To delete node having right hand child */
else if (t->l == NULL)
{
if (t1 == t)
{
root = t->r;
t1 = root;
}
else if (t1->r == t)
t1->r = t->r;
else
t1->l = t->r;
t == NULL;
free(t);
return;
}
/* To delete node having two child */
else if ((t->l != NULL) && (t->r != NULL))
{
t2 = root;
if (t->r != NULL)
{
k = smallest(t->r);
flag = 1;
}
else
{
k =largest(t->l);
flag = 2;
}
search1(root, k);
t->value = k;
}
}

LAB EXERCISE-6
Q1. Design and implement an algorithm to perform LEFT-ROTATE operation on
a binary search tree.
AlgorithmLEFT-ROTATE(T, x)
4. y right[x]
Set y
5. right[x] left[y] ys left subtree becomes xs right subtree
6. if left[y] NIL
7.
then p[left[y]] x Set the parent relation from left[y] to x
8. p[y] p[x]
The parent of x becomes the parent of y
9. if p[x] = NIL
10.
then root[T] y
11.
else if x = left[p[x]]
12.
then left[p[x]] y
13.
else right[p[x]] y
14.
left[y] x
Put x on ys left
15.
p[x] y
y becomes xs parent
Program#include<stdio.h>
#include<conio.h>
unsigned int leftrot(unsigned int x, unsigned int n);
void main()
{ unsigned int x,n,l;
clrscr();
printf("Enter the value of x and n\n");
scanf("%u%u",&x,&n);
l=leftrot(x,n);
printf("x=%u,n=%u,r=%u\n",x,n,r);
getch();
}
unsigned int rightrot(unsigned int x, unsigned int n)
{ unsigned int y,z,a;
a=x<<n;
z=x>>(16-n);
y=a+z;
return y;
}

Q2. Design and implement an algorithm to perform right rotate operation on a


binary search tree.
AlgorithmRIGHT-ROTATE(T, x)
y = x.left
// set y
x.left = y.right
// turn ys right sub tree into xs left sub tree
if y.right NULL
y.right.parent = x
y.parent = x.parent
// link xs parent to y
if x.parent == NULL
T.root = y
else if x == x.parent.left
x.parent.left = y
else
x.parent.right = y
y.right = x
// put x on ys right
x.parent = y
Program-

#include<stdio.h>
#include<conio.h>
unsigned int rightrot(unsigned int x, unsigned int n);
void main()
{ unsigned int x,n,r;
clrscr();
printf("Enter the value of x and n\n");
scanf("%u%u",&x,&n);
r=rightrot(x,n);
printf("x=%u,n=%u,r=%u\n",x,n,r);
getch();
}
unsigned int rightrot(unsigned int x, unsigned int n)
{ unsigned int y,z,a;
a=x>>n;
z=x<<(16-n);
y=a+z;
return y;
}

LAB EXERCISE-7
Design and implement an algorithm to insert any number of elements in REDBLACK Tree. Use the appropriate techniques to show the color of nodes also
and analyze its time complexity based on CPU utilization.
AlgorithmRB-INSERT(T, z)
15.
y NIL
16.
x root[T]
17.
while x NIL
18.
do y x
19.
if key[z] < key[x]
20.
then x left[x]
21.
else x right[x]
22.
p[z] y
8.
if y = NIL
9.
then root[T] z
10.
else if key[z] < key[y]
11.
then left[y] z
12.
else right[y] z
13.
left[z] NIL
14.
right[z] NIL
15.
color[z] RED
16.
RB-INSERT-FIXUP(T, z)
RB-INSERT-FIXUP(T, z)
16.
while color[p[z]] = RED
17.
do if p[z] = left[p[p[z]]]
18.
then y right[p[p[z]]]
19.
if color[y] = RED
20.
then Case1
21.
else if z = right[p[z]]
22.
then Case2
23.
Case3
24.
else (same as then clause with right and left
exchanged)
25.
color[root[T]] BLACK
RB-INSERT-FIXUP Case 1
(z is a right child)
11.
Color p[z] black
12.
Color y black
13.
Color p[p[z]] red
14.
z=p[p[z]]
(z is a left child)
11.
Color p[z]black
12.
Color yblack
13.
Color p[p[z]]red
14.
z=p[p[z]]
RB-INSERT-FIXUP Case 3
19.
zs uncle (y) is black
20.
z is a left child
24.
color p[z] black
25.
color p[p[z]] red

26.

RIGHT-ROTATE(T,p[p[z]])

RB-INSERT-FIXUP Case 2
zs uncle (y) is black
z is a right child
1. zp[z]
2. LEFT-ROTATE(T,z)
Program#include <cstdio>
#include <stdlib.h>
using namespace std;
enum nodeColor
{
RED,
BLACK
};
struct rbNode
{
int data, color;
struct rbNode *link[2];
};
struct rbNode *root = NULL;
struct rbNode *createNode(int data)
{
struct rbNode *newnode;
newnode = (struct rbNode *)malloc(sizeof(struct rbNode));
newnode->data = data;
newnode->color = RED;
newnode->link[0] = newnode->link[1] = NULL;
return newnode;
}
void insertion(int data)
{
struct rbNode *stack[98], *ptr, *newnode, *xPtr, *yPtr;
int dir[98], ht = 0, index;
ptr = root;
if (!root)
{
root = createNode(data);
return;
}
stack[ht] = root;
dir[ht++] = 0;
while (ptr != NULL)
{
if (ptr->data == data)
{
printf("Duplicates Not Allowed!!\n");
return;
}
index = (data - ptr->data) > 0 ? 1 : 0;
stack[ht] = ptr;
ptr = ptr->link[index];
dir[ht++] = index;
}
stack[ht - 1]->link[index] = newnode = createNode(data);
while ((ht >= 3) && (stack[ht - 1]->color == RED))
{
if (dir[ht - 2] == 0)
{
yPtr = stack[ht - 2]->link[1];
if (yPtr != NULL && yPtr->color == RED)
{
stack[ht - 2]->color = RED;
stack[ht - 1]->color = yPtr->color = BLACK;
ht = ht -2;
} else

{
if (dir[ht - 1] == 0)
{
yPtr = stack[ht - 1];
}
else
{
xPtr = stack[ht - 1];
yPtr = xPtr->link[1];
xPtr->link[1] = yPtr->link[0];
yPtr->link[0] = xPtr;
stack[ht - 2]->link[0] = yPtr;
}
xPtr = stack[ht - 2];
xPtr->color = RED;
yPtr->color = BLACK;
xPtr->link[0] = yPtr->link[1];
yPtr->link[1] = xPtr;
if (xPtr == root)
{
root = yPtr;
}
else
{
stack[ht - 3]->link[dir[ht - 3]] = yPtr;
}
break;
}
}
else
{
yPtr = stack[ht - 2]->link[0];
if ((yPtr != NULL) && (yPtr->color == RED))
{
stack[ht - 2]->color = RED;
stack[ht - 1]->color = yPtr->color = BLACK;
ht = ht - 2;
}
else
{
if (dir[ht - 1] == 1)
{
yPtr = stack[ht - 1];
} else
{
xPtr = stack[ht - 1];
yPtr = xPtr->link[0];
xPtr->link[0] = yPtr->link[1];
yPtr->link[1] = xPtr;
stack[ht - 2]->link[1] = yPtr;
}
xPtr = stack[ht - 2];
yPtr->color = BLACK;
xPtr->color = RED;
xPtr->link[1] = yPtr->link[0];
yPtr->link[0] = xPtr;
if (xPtr == root) {
root = yPtr;
}
else
{
stack[ht - 3]->link[dir[ht - 3]] = yPtr;
}
break;
}
}
}
root->color = BLACK;
}

int main()
{
int data;
printf("\nEnter the data to insert : ");
scanf("%d", &data);
insertion(data);
getch();
return 0;}

LAB EXERCISE-8
Design and implement an algorithm to delete any number of elements in REDBLACK Tree. Use the
appropriate techniques to show the color of nodes also and analyze its time
complexity on the basis of CPU utilization.
AlgorithmRB-DELETE(T, z)
1 if left[z] = nil[T] or right[z] = nil[T]
2 then y z
3 else y TREE-SUCCESSOR(z)
4 if left[y] nil[T]
5 then x left[y]
6 else x right[y]
7 p[x] p[y]
8 if p[y] = nil[T]
9 then root[T] x
10 else if y = left[p[y]]
11
then left[p[y]] x
12
else right[p[y]] x
13 if y != z
14 then key[z] key[y]
15
copy y's satellite data into z
16 if color[y] = BLACK
17 then RB-DELETE-FIXUP(T, x)
18 return y
TREE-SUCCESSOR(x)
1 if right[x] NIL
2
then return TREE-MINIMUM (right[x])
3 y p[x]
4 while y NIL and x = right[y]
5
do x y
6
y p[y]
7 return y
RB-DELETE-FIXUP(T, x)
1 while x root[T] and color[x] = BLACK
2
do if x = left[p[x]]
3
then w right[p[x]]
4
if color[w] = RED
5
then color[w] BLACK
Case 1
6
color[p[x]] RED
Case 1
7
LEFT-ROTATE(T, p[x])
Case 1
8
w right[p[x]]
Case 1
9
if color[left[w]] = BLACK and color[right[w]] = BLACK
10
then color[w] RED
Case 2
11
x p[x]
Case 2
12
else if color[right[w]] = BLACK
13
then color[left[w]] BLACK
Case 3
14
color[w] RED
Case 3
15
RIGHT-ROTATE(T, w)
Case 3
16
w right[p[x]]
Case 3
17
color[w] color[p[x]]
Case 4
18
color[p[x]] BLACK
Case 4
19
color[right[w]] BLACK
Case 4
20
LEFT-ROTATE(T, p[x])
Case 4
21
x root[T]
Case 4
22
else (same as then clause with "right" and "left" exchanged)
23 color[x] BLACK

Program#include <cstdio>
#include <stdlib.h>
using namespace std;
enum nodeColor
{
RED,
BLACK
};
struct rbNode

{
int data, color;
struct rbNode *link[2];
};
struct rbNode *root = NULL;
struct rbNode *createNode(int data)
{
struct rbNode *newnode;
newnode = (struct rbNode *)malloc(sizeof(struct rbNode));
newnode->data = data;
newnode->color = RED;
newnode->link[0] = newnode->link[1] = NULL;
return newnode;
}
void deletion(int data)
{
struct rbNode *stack[98], *ptr, *xPtr, *yPtr;
struct rbNode *pPtr, *qPtr, *rPtr;
int dir[98], ht = 0, diff, i;
int color;
if (!root)
{
printf("Tree not available\n");
return;
}
ptr = root;
while (ptr != NULL)
{
if ((data - ptr->data) == 0)
break;
diff = (data - ptr->data) > 0 ? 1 : 0;
stack[ht] = ptr;
dir[ht++] = diff;
ptr = ptr->link[diff];
}
if (ptr->link[1] == NULL)
{
if ((ptr == root) && (ptr->link[0] == NULL))
{
free(ptr);
root = NULL;
} else if (ptr == root)
{
root = ptr->link[0];
free(ptr);
} else
{
stack[ht - 1]->link[dir[ht - 1]] = ptr->link[0];
}
}
else
{
xPtr = ptr->link[1];
if (xPtr->link[0] == NULL)
{
xPtr->link[0] = ptr->link[0];
color = xPtr->color;
xPtr->color = ptr->color;
ptr->color = color;
if (ptr == root)
{
root = xPtr;
}
else
{
stack[ht - 1]->link[dir[ht - 1]] = xPtr;
}
dir[ht] = 1;

stack[ht++] = xPtr;
}
else
{
i = ht++;
while (1)
{
dir[ht] = 0;
stack[ht++] = xPtr;
yPtr = xPtr->link[0];
if (!yPtr->link[0])
break;
xPtr = yPtr;
}
dir[i] = 1;
stack[i] = yPtr;
if (i > 0)
stack[i - 1]->link[dir[i - 1]] = yPtr;
yPtr->link[0] = ptr->link[0];
xPtr->link[0] = yPtr->link[1];
yPtr->link[1] = ptr->link[1];
if (ptr == root)
{
root = yPtr;
}
color = yPtr->color;
yPtr->color = ptr->color;
ptr->color = color;
}
}
if (ht < 1)
return;
if (ptr->color == BLACK)
{
while (1)
{
pPtr = stack[ht - 1]->link[dir[ht - 1]];
if (pPtr && pPtr->color == RED)
{
pPtr->color = BLACK;
break;
}
if (ht < 2)
break;
if (dir[ht - 2] == 0)
{
rPtr = stack[ht - 1]->link[1];
if (!rPtr)
break;
if (rPtr->color == RED)
{
stack[ht - 1]->color = RED;
rPtr->color = BLACK;
stack[ht - 1]->link[1] = rPtr->link[0];
rPtr->link[0] = stack[ht - 1];
if (stack[ht - 1] == root)
{
root = rPtr;
}
else
{
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
dir[ht] = 0;
stack[ht] = stack[ht - 1];
stack[ht - 1] = rPtr;
ht++;
rPtr = stack[ht - 1]->link[1];

}
if ( (!rPtr->link[0] || rPtr->link[0]->color == BLACK) &&
(!rPtr->link[1] || rPtr->link[1]->color == BLACK))
{
rPtr->color = RED;
}
else
{
if (!rPtr->link[1] || rPtr->link[1]->color == BLACK)
{
qPtr = rPtr->link[0];
rPtr->color = RED;
qPtr->color = BLACK;
rPtr->link[0] = qPtr->link[1];
qPtr->link[1] = rPtr;
rPtr = stack[ht - 1]->link[1] = qPtr;
}
rPtr->color = stack[ht - 1]->color;
stack[ht - 1]->color = BLACK;
rPtr->link[1]->color = BLACK;
stack[ht - 1]->link[1] = rPtr->link[0];
rPtr->link[0] = stack[ht - 1];
if (stack[ht - 1] == root)
{
root = rPtr;
}
else
{
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
break;
}
}
else
{
rPtr = stack[ht - 1]->link[0];
if (!rPtr)
break;
if (rPtr->color == RED)
{
stack[ht - 1]->color = RED;
rPtr->color = BLACK;
stack[ht - 1]->link[0] = rPtr->link[1];
rPtr->link[1] = stack[ht - 1];
if (stack[ht - 1] == root)
{
root = rPtr;
}
else
{
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
dir[ht] = 1;
stack[ht] = stack[ht - 1];
stack[ht - 1] = rPtr;
ht++;
rPtr = stack[ht - 1]->link[0];
}
if ( (!rPtr->link[0] || rPtr->link[0]->color == BLACK) && (!rPtr->link[1] || rPtr->link[1]>color == BLACK))
{
rPtr->color = RED;
}
else
{
if (!rPtr->link[0] || rPtr->link[0]->color == BLACK)
{
qPtr = rPtr->link[1];
rPtr->color = RED;

qPtr->color = BLACK;
rPtr->link[1] = qPtr->link[0];
qPtr->link[0] = rPtr;
rPtr = stack[ht - 1]->link[0] = qPtr;
}
rPtr->color = stack[ht - 1]->color;
stack[ht - 1]->color = BLACK;
rPtr->link[0]->color = BLACK;
stack[ht - 1]->link[0] = rPtr->link[1];
rPtr->link[1] = stack[ht - 1];
if (stack[ht - 1] == root)
{
root = rPtr;
} else
{
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
break;
}
}
ht--;
}
}
}
int main()
{
int data;
printf("\nEnter the element to be deleted : ");
scanf("%d", &data);
deletion(data);
getch();
return 0;

LAB EXERCISE-9
Q1. Design and implement codes for basic operations for red black trees are
included in the book. Add to the code the following methods:
a. Delete a node from the red black tree.
b. Count the number of leaves in a tree.
c. Return the height of a tree.
d. Return a list of all keys in a tree between a and b.
Analyze the difference of time complexities on the basis of CPU utilization.
AlgorithmRB-INSERT(T, z)
23. y NIL
24. x root[T]
25. while x NIL
26.
do y x
27.
if key[z] < key[x]
28.
then x left[x]
29.
else x right[x]
30. p[z] y
17.
if y = NIL
18.
then root[T] z
19.
else if key[z] < key[y]
20.
then left[y] z
21.
else right[y] z
22. left[z] NIL
23. right[z] NIL
24. color[z] RED
25. RB-INSERT-FIXUP(T, z)
RB-INSERT-FIXUP(T, z)
26. while color[p[z]] = RED
27.
do if p[z] = left[p[p[z]]]
28.
then y right[p[p[z]]]
29.
if color[y] = RED
30.
then Case1
31.
else if z = right[p[z]]
32.
then Case2
33.
Case3
34.
else (same as then clause with right and left exchanged)
35. color[root[T]] BLACK
RB-INSERT-FIXUP Case 1
(z is a right child)
15. Color p[z] black
16. Color y black
17. Color p[p[z]] red
18. z=p[p[z]]
(z is a left child)
15. Color p[z]black
16. Color yblack
17. Color p[p[z]]red
18. z=p[p[z]]
RB-INSERT-FIXUP Case 3
21. zs uncle (y) is black
22. z is a left child
27. color p[z] black
28. color p[p[z]] red
29. RIGHT-ROTATE(T,p[p[z]])
RB-INSERT-FIXUP Case 2

zs uncle (y) is black

z is a right child
3. zp[z]
4. LEFT-ROTATE(T,z)
(a)RB-DELETE(T, z)
1 if left[z] = nil[T] or right[z] = nil[T]
2 then y z

3 else y TREE-SUCCESSOR(z)
4 if left[y] nil[T]
5 then x left[y]
6 else x right[y]
7 p[x] p[y]
8 if p[y] = nil[T]
9 then root[T] x
10 else if y = left[p[y]]
11
then left[p[y]] x
12
else right[p[y]] x
13 if y != z
14 then key[z] key[y]
15
copy y's satellite data into z
16 if color[y] = BLACK
17 then RB-DELETE-FIXUP(T, x)
18 return y
TREE-SUCCESSOR(x)
1 if right[x] NIL
2
then return TREE-MINIMUM (right[x])
3 y p[x]
4 while y NIL and x = right[y]
5
do x y
6
y p[y]
7 return y
RB-DELETE-FIXUP(T, x)
1 while x root[T] and color[x] = BLACK
2
do if x = left[p[x]]
3
then w right[p[x]]
4
if color[w] = RED
5
then color[w] BLACK
Case 1
6
color[p[x]] RED
Case 1
7
LEFT-ROTATE(T, p[x])
Case 1
8
w right[p[x]]
Case 1
9
if color[left[w]] = BLACK and color[right[w]] = BLACK
10
then color[w] RED
Case 2
11
x p[x]
Case 2
12
else if color[right[w]] = BLACK
13
then color[left[w]] BLACK
Case 3
14
color[w] RED
Case 3
15
RIGHT-ROTATE(T, w)
Case 3
16
w right[p[x]]
Case 3
17
color[w] color[p[x]]
Case 4
18
color[p[x]] BLACK
Case 4
19
color[right[w]] BLACK
Case 4
20
LEFT-ROTATE(T, p[x])
Case 4
21
x root[T]
Case 4
22
else (same as then clause with "right" and "left" exchanged)
23 color[x] BLACK

Program#include <cstdio>
#include <stdlib.h>
using namespace std;
enum nodeColor
{
RED,
BLACK
};
struct rbNode
{
int data, color;
struct rbNode *link[2];
};
struct rbNode *root = NULL;
struct rbNode *createNode(int data)

{
struct rbNode *newnode;
newnode = (struct rbNode *)malloc(sizeof(struct rbNode));
newnode->data = data;
newnode->color = RED;
newnode->link[0] = newnode->link[1] = NULL;
return newnode;
}
void insertion(int data)
{
struct rbNode *stack[98], *ptr, *newnode, *xPtr, *yPtr;
int dir[98], ht = 0, index;
ptr = root;
if (!root)
{
root = createNode(data);
return;
}
stack[ht] = root;
dir[ht++] = 0;
while (ptr != NULL)
{
if (ptr->data == data)
{
printf("Duplicates Not Allowed!!\n");
return;
}
index = (data - ptr->data) > 0 ? 1 : 0;
stack[ht] = ptr;
ptr = ptr->link[index];
dir[ht++] = index;
}
stack[ht - 1]->link[index] = newnode = createNode(data);
while ((ht >= 3) && (stack[ht - 1]->color == RED))
{
if (dir[ht - 2] == 0)
{
yPtr = stack[ht - 2]->link[1];
if (yPtr != NULL && yPtr->color == RED)
{
stack[ht - 2]->color = RED;
stack[ht - 1]->color = yPtr->color = BLACK;
ht = ht -2;
} else
{
if (dir[ht - 1] == 0)
{
yPtr = stack[ht - 1];
}
else
{
xPtr = stack[ht - 1];
yPtr = xPtr->link[1];
xPtr->link[1] = yPtr->link[0];
yPtr->link[0] = xPtr;
stack[ht - 2]->link[0] = yPtr;
}
xPtr = stack[ht - 2];
xPtr->color = RED;
yPtr->color = BLACK;
xPtr->link[0] = yPtr->link[1];
yPtr->link[1] = xPtr;
if (xPtr == root)
{

root = yPtr;
}
else
{
stack[ht - 3]->link[dir[ht - 3]] = yPtr;
}
break;
}
}
else
{
yPtr = stack[ht - 2]->link[0];
if ((yPtr != NULL) && (yPtr->color == RED))
{
stack[ht - 2]->color = RED;
stack[ht - 1]->color = yPtr->color = BLACK;
ht = ht - 2;
}
else
{
if (dir[ht - 1] == 1)
{
yPtr = stack[ht - 1];
} else
{
xPtr = stack[ht - 1];
yPtr = xPtr->link[0];
xPtr->link[0] = yPtr->link[1];
yPtr->link[1] = xPtr;
stack[ht - 2]->link[1] = yPtr;
}
xPtr = stack[ht - 2];
yPtr->color = BLACK;
xPtr->color = RED;
xPtr->link[1] = yPtr->link[0];
yPtr->link[0] = xPtr;
if (xPtr == root) {
root = yPtr;
}
else
{
stack[ht - 3]->link[dir[ht - 3]] = yPtr;
}
break;
}
}
}
root->color = BLACK;
}
void deletion(int data)
{
struct rbNode *stack[98], *ptr, *xPtr, *yPtr;
struct rbNode *pPtr, *qPtr, *rPtr;
int dir[98], ht = 0, diff, i;
int color;
if (!root)
{
printf("Tree not available\n");
return;
}
ptr = root;
while (ptr != NULL)

{
if ((data - ptr->data) == 0)
break;
diff = (data - ptr->data) > 0 ? 1 : 0;
stack[ht] = ptr;
dir[ht++] = diff;
ptr = ptr->link[diff];
}
if (ptr->link[1] == NULL)
{
if ((ptr == root) && (ptr->link[0] == NULL))
{
free(ptr);
root = NULL;
} else if (ptr == root)
{
root = ptr->link[0];
free(ptr);
} else
{
stack[ht - 1]->link[dir[ht - 1]] = ptr->link[0];
}
}
else
{
xPtr = ptr->link[1];
if (xPtr->link[0] == NULL)
{
xPtr->link[0] = ptr->link[0];
color = xPtr->color;
xPtr->color = ptr->color;
ptr->color = color;
if (ptr == root)
{
root = xPtr;
}
else
{
stack[ht - 1]->link[dir[ht - 1]] = xPtr;
}
dir[ht] = 1;
stack[ht++] = xPtr;
}
else
{
i = ht++;
while (1)
{
dir[ht] = 0;
stack[ht++] = xPtr;
yPtr = xPtr->link[0];
if (!yPtr->link[0])
break;
xPtr = yPtr;
}
dir[i] = 1;
stack[i] = yPtr;
if (i > 0)
stack[i - 1]->link[dir[i - 1]] = yPtr;
yPtr->link[0] = ptr->link[0];
xPtr->link[0] = yPtr->link[1];
yPtr->link[1] = ptr->link[1];
if (ptr == root)

{
root = yPtr;
}
color = yPtr->color;
yPtr->color = ptr->color;
ptr->color = color;
}
}
if (ht < 1)
return;
if (ptr->color == BLACK)
{
while (1)
{
pPtr = stack[ht - 1]->link[dir[ht - 1]];
if (pPtr && pPtr->color == RED)
{
pPtr->color = BLACK;
break;
}
if (ht < 2)
break;
if (dir[ht - 2] == 0)
{
rPtr = stack[ht - 1]->link[1];
if (!rPtr)
break;
if (rPtr->color == RED)
{
stack[ht - 1]->color = RED;
rPtr->color = BLACK;
stack[ht - 1]->link[1] = rPtr->link[0];
rPtr->link[0] = stack[ht - 1];
if (stack[ht - 1] == root)
{
root = rPtr;
}
else
{
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
dir[ht] = 0;
stack[ht] = stack[ht - 1];
stack[ht - 1] = rPtr;
ht++;
rPtr = stack[ht - 1]->link[1];
}
if ( (!rPtr->link[0] || rPtr->link[0]->color == BLACK) &&
(!rPtr->link[1] || rPtr->link[1]->color == BLACK))
{
rPtr->color = RED;
}
else
{
if (!rPtr->link[1] || rPtr->link[1]->color == BLACK)
{

qPtr = rPtr->link[0];
rPtr->color = RED;
qPtr->color = BLACK;
rPtr->link[0] = qPtr->link[1];
qPtr->link[1] = rPtr;
rPtr = stack[ht - 1]->link[1] = qPtr;
}
rPtr->color = stack[ht - 1]->color;
stack[ht - 1]->color = BLACK;
rPtr->link[1]->color = BLACK;
stack[ht - 1]->link[1] = rPtr->link[0];
rPtr->link[0] = stack[ht - 1];
if (stack[ht - 1] == root)
{
root = rPtr;
}
else
{
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
break;
}
}
else
{
rPtr = stack[ht - 1]->link[0];
if (!rPtr)
break;
if (rPtr->color == RED)
{
stack[ht - 1]->color = RED;
rPtr->color = BLACK;
stack[ht - 1]->link[0] = rPtr->link[1];
rPtr->link[1] = stack[ht - 1];
if (stack[ht - 1] == root)
{
root = rPtr;
}
else
{
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
dir[ht] = 1;
stack[ht] = stack[ht - 1];
stack[ht - 1] = rPtr;
ht++;
rPtr = stack[ht - 1]->link[0];
}
if ( (!rPtr->link[0] || rPtr->link[0]->color == BLACK) && (!rPtr->link[1] || rPtr->link[1]>color == BLACK))
{
rPtr->color = RED;
}
else
{
if (!rPtr->link[0] || rPtr->link[0]->color == BLACK)
{
qPtr = rPtr->link[1];
rPtr->color = RED;
qPtr->color = BLACK;
rPtr->link[1] = qPtr->link[0];
qPtr->link[0] = rPtr;
rPtr = stack[ht - 1]->link[0] = qPtr;
}
rPtr->color = stack[ht - 1]->color;

stack[ht - 1]->color = BLACK;


rPtr->link[0]->color = BLACK;
stack[ht - 1]->link[0] = rPtr->link[1];
rPtr->link[1] = stack[ht - 1];
if (stack[ht - 1] == root)
{
root = rPtr;
} else
{
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
break;
}
}
ht--;
}
}
}
int main()
{
int ch, data;
while (1)
{
printf("1. Insert a new element\n2. Delete an element\n");
scanf("%d", &ch);
switch (ch)
{
case 1:
{
printf("\nEnter the data to insert : ");
scanf("%d", &data);
insertion(data);
break;
}
case 2:
{
printf("\nEnter the element to be deleted : ");
scanf("%d", &data);
deletion(data);
break;
}
}
printf("\n");
}
return 0;
}

(b)AlgorithmgetLeafCount(struct node* node)


1. if(node=NULL)
2. return 0
3. if(node->left=NULL and node->right=NULL)
4. return 1
5. else
6. return getLeafCount(node->left)+getLeafCount(node->right)

Program#include <stdio.h>
#include <stdlib.h>
struct node

{
int data;
struct node* left;
struct node* right;
};
unsigned int getLeafCount(struct node* node)
{
if(node == NULL)
return 0;
if(node->left == NULL && node->right==NULL)
return 1;
else
return getLeafCount(node->left)+getLeafCount(node->right);
}
int main()
{
struct node *root = newNode(1);
root->left
root->right

= newNode(2);
= newNode(3);

root->left->left = newNode(4);
root->left->right = newNode(5);
printf("Leaf count of the tree is %d", getLeafCount(root));
getchar();
return 0;
}

LAB EXERCISE-10
Q1. Design and implement codes for the construction of AVL tree having any
number of nodes given by user and perform single and double rotation as per
the requirement of AVL tree. Analyze its time complexity on the basis of CPU
utilization.
Program#include<stdio.h>
#include<stdlib.h>
// An AVL tree node
struct node
{
int key;
struct node *left;
struct node *right;
int height;
};
// A utility function to get maximum of two integers
int max(int a, int b);
// A utility function to get height of the tree
int height(struct node *N)
{
if (N == NULL)
return 0;
return N->height;
}
// A utility function to get maximum of two integers
int max(int a, int b)
{
return (a > b)? a : b;
}
/* Helper function that allocates a new node with the given key and
NULL left and right pointers. */
struct node* newNode(int key)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1; // new node is initially added at leaf
return(node);
}
// A utility function to right rotate subtree rooted with y
// See the diagram given above.
struct node *rightRotate(struct node *y)
{
struct node *x = y->left;
struct node *T2 = x->right;
// Perform rotation
x->right = y;
y->left = T2;
// Update heights
y->height = max(height(y->left), height(y->right))+1;
x->height = max(height(x->left), height(x->right))+1;
// Return new root
return x;
}
// A utility function to left rotate subtree rooted with x
// See the diagram given above.
struct node *leftRotate(struct node *x)
{
struct node *y = x->right;
struct node *T2 = y->left;
// Perform rotation
y->left = x;
x->right = T2;
// Update heights

x->height = max(height(x->left), height(x->right))+1;


y->height = max(height(y->left), height(y->right))+1;
// Return new root
return y;
}
// Get Balance factor of node N
int getBalance(struct node *N)
{
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
struct node* insert(struct node* node, int key)
{
/* 1. Perform the normal BST rotation */
if (node == NULL)
return(newNode(key));
if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);
/* 2. Update height of this ancestor node */
node->height = max(height(node->left), height(node->right)) + 1;
/* 3. Get the balance factor of this ancestor node to check whether
this node became unbalanced */
int balance = getBalance(node);
// If this node becomes unbalanced, then there are 4 cases
// Left Left Case
if (balance > 1 && key < node->left->key)
return rightRotate(node);
// Right Right Case
if (balance < -1 && key > node->right->key)
return leftRotate(node);
// Left Right Case
if (balance > 1 && key > node->left->key)
{
node->left = leftRotate(node->left);
return rightRotate(node);
}
// Right Left Case
if (balance < -1 && key < node->right->key)
{
node->right = rightRotate(node->right);
return leftRotate(node);
}
/* return the (unchanged) node pointer */
return node;
}
// A utility function to print preorder traversal of the tree.
// The function also prints height of every node
void preOrder(struct node *root)
{
if(root != NULL)
{
printf("%d ", root->key);
preOrder(root->left);
preOrder(root->right);
}
}
/* Driver program to test above function*/
int main()
{
struct node *root = NULL;
/* Constructing tree given in the above figure */
root = insert(root, 10);
root = insert(root, 20);
root = insert(root, 30);
root = insert(root, 40);
root = insert(root, 50);

root = insert(root, 25);


/* The constructed AVL Tree would be
30
/ \
20 40
/ \
\
10 25 50
*/
printf("Pre order traversal of the constructed AVL tree is \n");
preOrder(root);
return 0;
}

LAB EXERCISE-11
Design and implement algorithm for B-Tree with t(minimum degree of tree) =3
for following
operations:
(A) B-Tree Search
(B) B-Tree Create
(C) B-Tree Insert
Analyze its time complexities on the basis of CPU utilization and justify it.
Program#include <stdio.h>
#include <stdlib.h>
#define MAX 4
#define MIN 2
struct btreeNode {
int val[MAX + 1], count;
struct btreeNode *link[MAX + 1];
};
struct btreeNode *root;
/* creating new node */
struct btreeNode * createNode(int val, struct btreeNode *child) {
struct btreeNode *newNode;
newNode = (struct btreeNode *)malloc(sizeof(struct btreeNode));
newNode->val[1] = val;
newNode->count = 1;
newNode->link[0] = root;
newNode->link[1] = child;
return newNode;
}
/* Places the value in appropriate position */
void addValToNode(int val, int pos, struct btreeNode *node,
struct btreeNode *child) {
int j = node->count;
while (j > pos) {
node->val[j + 1] = node->val[j];
node->link[j + 1] = node->link[j];
j--;
}
node->val[j + 1] = val;
node->link[j + 1] = child;
node->count++;
}
/* split the node */
void splitNode (int val, int *pval, int pos, struct btreeNode *node,
struct btreeNode *child, struct btreeNode **newNode) {
int median, j;
if (pos > MIN)
median = MIN + 1;
else
median = MIN;
*newNode = (struct btreeNode *)malloc(sizeof(struct btreeNode));
j = median + 1;
while (j <= MAX) {
(*newNode)->val[j - median] = node->val[j];
(*newNode)->link[j - median] = node->link[j];
j++;
}
node->count = median;
(*newNode)->count = MAX - median;
if (pos <= MIN) {
addValToNode(val, pos, node, child);
} else {
addValToNode(val, pos - median, *newNode, child);
}
*pval = node->val[node->count];
(*newNode)->link[0] = node->link[node->count];
node->count--;

}
/* sets the value val in the node */
int setValueInNode(int val, int *pval,
struct btreeNode *node, struct btreeNode **child) {
int pos;
if (!node) {
*pval = val;
*child = NULL;
return 1;
}
if (val < node->val[1]) {
pos = 0;
} else {
for (pos = node->count;
(val < node->val[pos] && pos > 1); pos--);
if (val == node->val[pos]) {
printf("Duplicates not allowed\n");
return 0;
}
}
if (setValueInNode(val, pval, node->link[pos], child)) {
if (node->count < MAX) {
addValToNode(*pval, pos, node, *child);
} else {
splitNode(*pval, pval, pos, node, *child, child);
return 1;
}
}
return 0;
}
/* insert val in B-Tree */
void insertion(int val) {
int flag, i;
struct btreeNode *child;
flag = setValueInNode(val, &i, root, &child);
if (flag)
root = createNode(i, child);
}
/* copy successor for the value to be deleted */
void copySuccessor(struct btreeNode *myNode, int pos) {
struct btreeNode *dummy;
dummy = myNode->link[pos];
for (;dummy->link[0] != NULL;)
dummy = dummy->link[0];
myNode->val[pos] = dummy->val[1];
}
/* removes the value from the given node and rearrange values */
void removeVal(struct btreeNode *myNode, int pos) {
int i = pos + 1;
while (i <= myNode->count) {
myNode->val[i - 1] = myNode->val[i];
myNode->link[i - 1] = myNode->link[i];
i++;
}
myNode->count--;
}
/* shifts value from parent to right child */
void doRightShift(struct btreeNode *myNode, int pos) {
struct btreeNode *x = myNode->link[pos];
int j = x->count;
while (j > 0) {
x->val[j + 1] = x->val[j];
x->link[j + 1] = x->link[j];
}
x->val[1] = myNode->val[pos];
x->link[1] = x->link[0];
x->count++;
x = myNode->link[pos - 1];

myNode->val[pos] = x->val[x->count];
myNode->link[pos] = x->link[x->count];
x->count--;
return;
}
/* shifts value from parent to left child */
void doLeftShift(struct btreeNode *myNode, int pos) {
int j = 1;
struct btreeNode *x = myNode->link[pos - 1];
x->count++;
x->val[x->count] = myNode->val[pos];
x->link[x->count] = myNode->link[pos]->link[0];
x = myNode->link[pos];
myNode->val[pos] = x->val[1];
x->link[0] = x->link[1];
x->count--;
while (j <= x->count) {
x->val[j] = x->val[j + 1];
x->link[j] = x->link[j + 1];
j++;
}
return;
}
/* merge nodes */
void mergeNodes(struct btreeNode *myNode, int pos) {
int j = 1;
struct btreeNode *x1 = myNode->link[pos], *x2 = myNode->link[pos - 1];
x2->count++;
x2->val[x2->count] = myNode->val[pos];
x2->link[x2->count] = myNode->link[0];
while (j <= x1->count) {
x2->count++;
x2->val[x2->count] = x1->val[j];
x2->link[x2->count] = x1->link[j];
j++;
}
j = pos;
while (j < myNode->count) {
myNode->val[j] = myNode->val[j + 1];
myNode->link[j] = myNode->link[j + 1];
j++;
}
myNode->count--;
free(x1);
}
/* adjusts the given node */
void adjustNode(struct btreeNode *myNode, int pos) {
if (!pos) {
if (myNode->link[1]->count > MIN) {
doLeftShift(myNode, 1);
} else {
mergeNodes(myNode, 1);
}
} else {
if (myNode->count != pos) {
if(myNode->link[pos - 1]->count > MIN) {
doRightShift(myNode, pos);
} else {
if (myNode->link[pos + 1]->count > MIN) {
doLeftShift(myNode, pos + 1);
} else {
mergeNodes(myNode, pos);
}
}
} else {
if (myNode->link[pos - 1]->count > MIN)
doRightShift(myNode, pos);
else
mergeNodes(myNode, pos);

}
}
}
/* delete val from the node */
int delValFromNode(int val, struct btreeNode *myNode) {
int pos, flag = 0;
if (myNode) {
if (val < myNode->val[1]) {
pos = 0;
flag = 0;
} else {
for (pos = myNode->count;
(val < myNode->val[pos] && pos > 1); pos--);
if (val == myNode->val[pos]) {
flag = 1;
} else {
flag = 0;
}
}
if (flag) {
if (myNode->link[pos - 1]) {
copySuccessor(myNode, pos);
flag = delValFromNode(myNode->val[pos], myNode->link[pos]);
if (flag == 0) {
printf("Given data is not present in B-Tree\n");
}
} else {
removeVal(myNode, pos);
}
} else {
flag = delValFromNode(val, myNode->link[pos]);
}
if (myNode->link[pos]) {
if (myNode->link[pos]->count < MIN)
adjustNode(myNode, pos);
}
}
return flag;
}
/* delete val from B-tree */
void deletion(int val, struct btreeNode *myNode) {
struct btreeNode *tmp;
if (!delValFromNode(val, myNode)) {
printf("Given value is not present in B-Tree\n");
return;
} else {
if (myNode->count == 0) {
tmp = myNode;
myNode = myNode->link[0];
free(tmp);
}
}
root = myNode;
return;
}
/* search val in B-Tree */
void searching(int val, int *pos, struct btreeNode *myNode) {
if (!myNode) {
return;
}
if (val < myNode->val[1]) {
*pos = 0;
} else {
for (*pos = myNode->count;
(val < myNode->val[*pos] && *pos > 1); (*pos)--);
if (val == myNode->val[*pos]) {
printf("Given data %d is present in B-Tree", val);
return;
}

}
searching(val, pos, myNode->link[*pos]);
return;
}
/* B-Tree Traversal */
void traversal(struct btreeNode *myNode) {
int i;
if (myNode) {
for (i = 0; i < myNode->count; i++) {
traversal(myNode->link[i]);
printf("%d ", myNode->val[i + 1]);
}
traversal(myNode->link[i]);
}
}
int main() {
int val, ch;
while (1) {
printf("1. Insertion\t2. Deletion\n");
printf("3. Searching\t4. Traversal\n");
printf("5. Exit\nEnter your choice:");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("Enter your input:");
scanf("%d", &val);
insertion(val);
break;
case 2:
printf("Enter the element to delete:");
scanf("%d", &val);
deletion(val, root);
break;
case 3:
printf("Enter the element to search:");
scanf("%d", &val);
searching(val, &ch, root);
break;
case 4:
traversal(root);
break;
case 5:
exit(0);
default:
printf("U have entered wrong option!!\n");
break;
}
printf("\n");
}
}

Das könnte Ihnen auch gefallen