Skip to content

Instantly share code, notes, and snippets.

@pi8027
Created August 4, 2009 02:39
Show Gist options
  • Save pi8027/160992 to your computer and use it in GitHub Desktop.
Save pi8027/160992 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
static int mergesort_(void *base,const size_t num,const size_t size
,int (*compare)(const void *,const void *),int *temp)
{
size_t counter_a = 0,counter_b = 0;
if(size != 1){
mergesort_(array,size>>1,temp);
mergesort_(&array[size>>1],size-(size>>1),temp);
while(counter_a != size>>1 && (size>>1)+counter_b != size){
if(array[counter_a] <= array[(size>>1)+counter_b]){
temp[counter_a+counter_b] = array[counter_a];
counter_a++;
}
else{
temp[counter_a+counter_b] = array[(size>>1)+counter_b];
counter_b++;
}
}
if(counter_a != size>>1){
memcpy(&array[counter_a+counter_b],&array[counter_a]
,sizeof(int)*(size-counter_a-counter_b));
}
memcpy(array,temp,sizeof(int)*(counter_a+counter_b));
}
}
int mergesort(void *base,const size_t num,const size_t size
,int (*compare)(const void *,const void *))
{
int *temp = malloc(sizeof(size)*size);
if(!temp){
return -1;
}
mergesort_(base,num,size,compare,temp);
free(temp);
return 0;
}
int compare_integer(const void *a,const void *b)
{
return *(int *)a-*(int *)b;
}
int main(void)
{
int array[10] = {6,6,1,4,2,9,3,7,10,8};
size_t counter = 0;
mergesort(array,10,sizeof(int),compare_integer);
while(counter != 10){
printf("%d ",array[counter]);
counter++;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment