-
Notifications
You must be signed in to change notification settings - Fork 1
/
merge_sort.c
71 lines (62 loc) · 1.32 KB
/
merge_sort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include "stdio.h"
#include "stdlib.h"
typedef int(*DataCompareFunc)(void *ctc,void *data);
int int_cmp(void *a,void *b)
{
return (int)a - (int)b;
}
static void merge_sort_impl(void **storage,void **array,size_t low,size_t mid,size_t high,DataCompareFunc cmp)
{
size_t i = low;
size_t j = low;
size_t k = mid;
if((low+1) < mid)
{
size_t x = low + ((mid - low) >> 1);
merge_sort_impl(storage,array,low,x,mid,cmp);
}
if((mid+1) < high)
{
size_t x = mid + ((high-mid) >> 1);
merge_sort_impl(storage,array,mid,x,high,cmp);
}
while(j < mid && k < high)
{
if(cmp(array[j],array[k]) <= 0)
{
storage[i++] = array[j++];
}
else
{
storage[i++] = array[k++];
}
}
while(j < mid)
{
storage[i++] = array[j++];
}
while(k < high)
{
storage[i++] = array[k++];
}
for(i = low; i< high;i++)
{
array[i] = storage[i];
}
return 0;
}
void merge_sort(void **array,size_t nr,DataCompareFunc cmp)
{
void **storage = NULL;
int ret_val = 0;
if(nr > 1)
{
storage = (void**)malloc(sizeof(void *) * nr);
if(storage != NULL)
{
ret_val = merge_sort_impl(storage,array,0,nr>>1,nr,cmp);
free(storage);
}
}
return ret_val;
}