Skip to content

Instantly share code, notes, and snippets.

@hfadev
Created July 30, 2012 02:09
Show Gist options
  • Select an option

  • Save hfadev/3203357 to your computer and use it in GitHub Desktop.

Select an option

Save hfadev/3203357 to your computer and use it in GitHub Desktop.
C: Merge Sort
void merge(int* a, int n);
void mergeSort(int* a, int n);
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define NUM_ELEMENTS_IN(t) (sizeof(t)/sizeof(*t))
int main(int argc, char const *argv[])
{
int a[] = {3,4,5,1,-1,-2,99,6};
int i;
mergeSort(a,NUM_ELEMENTS_IN(a));
for (i = 0; i < NUM_ELEMENTS_IN(a); ++i)
{
printf("%d ",a[i]);
}
return 0;
}
void mergeSort(int* a, int n){
if( n <= 1 ){
return;
}
mergeSort(a, n/2 );
mergeSort(a + n/2, n - n/2);
merge(a, n );
}
//merge n/2 from beginning with
//n - n/2 elements from n/2+1 element
//which are sorted in increased order themselves
void merge(int* a, int n){
int i,k = 0,m = 0;
int* temp = (int*)malloc(sizeof(int) * n);
for (i = 0; (i < n) && (k < n/2) && (m < (n-n/2)) ; ++i)
{
if( a[k] < a[n/2+m]){
temp[i] = a[k];
k++;
}else{
temp[i] = a[n/2+m];
m++;
}
}
if( k < n/2 ){
for( ;k < n/2;k++ ){
temp[i++] = a[k];
}
}else if( m < (n-n/2)){
for(; m < (n-n/2); m++){
temp[i++] = a[n/2+m];
}
}
memcpy(a,temp,sizeof(int) * n);
free(temp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment