Merge Sort
#include <stdio.h>
#include <stdlib.h>
void print_array(int array[],int size)
{
int i;
for(i = 0;i<size;i++)
{
printf("%d ,",array[i]);
}
}
void merge(int array[],int l,int mid,int h)
{
int i,j,k;
int n1 = mid-l+1;//left sub
int n2 = h-mid;
int left[n1],right[n2];
for(i = 0;i<n1;i++)
{
left[i] = array[l+i];
}
for(j = 0;j<n2;j++)
{
right[j] = array[mid+1+j];
}
i = 0;
j = 0;
k = l;
while(i<n1 && j<n2)
{
if(left[i] <=right[j])
{
array[k] = left[i];
i++;
}
else
{
array[k] = right[j];
j++;
}
k++;
}
while(i<n1)
{
array[k] = left[i];
i++;
k++;
}
while(j<n2)
{
array[k] = right[j];
j++;
k++;
}
}
void mergesort(int array[],int l,int h)
{
if(l<h)
{
int mid = (l+h)/2;
mergesort(array,l,mid);
mergesort(array,mid+1,h);
merge(array,l,mid,h);
}
}
int main()
{
int array[7] = {10,3,12,32,7,20,4};
mergesort(array,0,6);
print_array(array,7);
return 0;
}
Komentar
Posting Komentar