Merge Sort iterative way

recursive way is very easy to write for merge sort. generally interviewers now a days asking for iterative way..here is mergesort in iterative way. this prints elements in ascending manner.

NOTE: some of greater , lesser operators could be missing due to bloging issues .


#include
#include
#include
using namespace std  ;

void merge(int [],int,int,int);
int main()
{
int a[100];

int j=0,size=0;
for(int i=10;i > =0; i--){
++size;
a[j++]=i;
}

int mergelen=2,start=0;
int i=0;
int mid=0;
int lastmerge=0;
while(mergelen < size)
{

for(i=0;i < size; i=i+mergelen)
{
if((i+mergelen) < size){
mid=i+mergelen/2 ;
merge(a,i,i+mergelen-1,mid);
}
else{
mid=(i+(size))/2;
merge(a,i,size-1,mid+1);
}
lastmerge=i;
}
mergelen=mergelen * 2 ;
}
merge(a,0,size-1,lastmerge);
cout<<"final"<
//print elements here.
getchar();return 0;
}


void merge(int a[],int start,int mergelen,int size)
{
cout<<"\n pass "<
int temp[100];
//cout<<"\n pivot is "<
int i=start,j=size,k=0;
while(i < size && j <= mergelen)
{
//cout<<"\n exchanging "<
if(a[i]>a[j]){
temp[k]=a[j];
k++;j++;
}
else{
temp[k]=a[i];
k++;i++;
}
}
while(i < size )
temp[k++]=a[i++];

while(j < = mergelen)
temp[k++]=a[j++];


for(int index=0;index < k ; index=index+1)
a[start++]=temp[index];

}




No comments: