Merge sort in C code

/* Merge Sort*/


#include<stdio.h>
#define MAX 100


void merge(int *arr,int *order,int low,int mid,int high)
{
int i,j,k,temp[MAX],ord[MAX];
i=low;
j=mid+1;
k=low;
while(i<=mid && j<=high)
{
if(arr[i]<arr[j])
{
temp[k]=arr[i];
ord[k]=order[i];
i++;
k++;
}
else
{
temp[k]=arr[j];
ord[k]=order[j];
j++;
k++;
}
}
if(i>mid)
{
while(j<=high)
{
temp[k]=arr[j];
ord[k]=order[j];
k++;
j++;
}
}
else
{
while(i<=mid)
{
temp[k]=arr[i];
ord[k]=order[i];
k++;
i++;
}
}

for(i=low;i<=high;i++)
{
arr[i]=temp[i];
order[i]=ord[i];
}
}

void divided(int *arr,int *ord,int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
divided(arr,ord,low,mid);
divided(arr,ord,mid+1,high);
merge(arr,ord,low,mid,high);
}
}

void merge_sort(int *arr,int *ord,int low,int high)
{
for(int i=0;i<=high;i++)
ord[i]=i;
divided(arr,ord,low,high);
}


int main()
{
int arr[10],index[10],n,i,x;
freopen("in.txt","r",stdin);
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&x);
arr[i]=x;
}
merge_sort(arr,index,0,n-1);
for(i=0;i<n;i++)
printf("%d ",arr[i]);
printf("\n");
for(i=0;i<n;i++)
printf("%d ",index[i]);
return 0;
}

Comments

Popular posts from this blog

uva 679 - Dropping Balls Solution

uva 481 - What Goes Up Solution

uva-10077 Solution --- The Stern-Brocot Number System