Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Heap Sort (using random input)

Source Code:

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
#include<math.h>
#define MAXSIZE RAND_MAX



void MAX_HEAPIFY(int *A, int i, int n);
void BUILD_MAX_HEAP(int *A, int n);
void HEAP_SORT(int *A, int n);
int RECURSIVE_BINARY_SEARCH(int *A, int s,int e, int key)
{
int mid=ceil((s+e)/2);
if(A[mid]==key)
{
return mid;
}
if(s>=e)
{
return -1;
}
if(A[mid]>key)
{
return RECURSIVE_BINARY_SEARCH(A,s,mid-1,key);
}
else
{
return RECURSIVE_BINARY_SEARCH(A,mid+1,e,key);
}
}


//function to get a random number between 1 and max
int GetRandom(int max)
{
return rand()%max +1;
}
//create an input array of size n by assigning random integers
//from 1 to n at each location
int* createRandomInput(int n)
{
int *A= new int[n];
for(int i=0;i<n;i++){
A[i]=GetRandom(n);
}
return(A);
}
void MAX_HEAPIFY(int *A,int i,int n)
{
int l,r,largest=i,x;
l=2*(i+1) -1;
r=2*(i+1);
if((l<n)&& (A[l]>A[i]))
largest=l;
if(r<n && A[r]>A[largest])
largest=r;
if(largest!=i)
{
x=A[i];
A[i]=A[largest];
A[largest]=x;
MAX_HEAPIFY(A,largest,n);
}
}

void BUILD_MAX_HEAP(int *A,int n)
{
int i;
for(i=n/2;i>=0;i--)
{
MAX_HEAPIFY(A,i,n);
}
}

void HEAP_SORT(int *A,int n)
{
int i,x;
for(i=0;i<=n-1;i++)
{
x=A[0];
A[0]=A[n-i-1];
A[n-i-1]=x;

MAX_HEAPIFY(A,0,n-i-1);
}
}
void main()
{
int n,*A;
clrscr();
cout<<"Program for HEAP SORT (using random input array)by-Tarun rawat\n\n ";
//take size of input from user between 1 and maxsize
//check for correctness
n=0;
while(n<=0 || n>MAXSIZE)
{
cout<<"Please define input size between 1 and "<<MAXSIZE<<":";
cin>>n;
}
//create random array
A=createRandomInput(n);
//Note-This is for our test for now.
//right now
//output array to the user
for(int i=0;i<n;i++)
{
cout<<A[i]<<",";
}
cout<<"\n";
BUILD_MAX_HEAP(A,n);
HEAP_SORT(A,n);
for(i=0;i<n;i++)
{
cout<<A[i]<<",";
}
int key;
cout<<"\n enter the element to be searched:";
cin>>key;
int loc=RECURSIVE_BINARY_SEARCH(A,0,n-1,key);
cout<<"\nthe element found at:"<< loc;
if(loc!=-1)
{
cout<<"\nelement found is:"<<key;
}
else
{
cout<<"\nelement not found ";
}
getch();
}

1 comment:

Blogger Widgets

Find Us On Google, Just type - way2cplusplus -

If you have any questions on implementing or understanding this C++ Program , shoot me a comment and I'll be glad to help! :) :)