Make duplicate script compatible with Python 3
[wdl/wdl-ol.git] / WDL / mergesort.h
blob9c8c28c21f42b93c2120ee4f9861b16b6c1bbb32
1 #ifndef _WDL_MERGESORT_H_
2 #define _WDL_MERGESORT_H_
5 static void WDL_mergesort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *), char *tmpspace)
7 char *b1,*b2;
8 size_t n1, n2;
10 if (nmemb < 2) return;
12 n1 = nmemb / 2;
13 b1 = (char *) base;
14 n2 = nmemb - n1;
15 b2 = b1 + (n1 * size);
17 if (nmemb>2)
19 WDL_mergesort(b1, n1, size, compar, tmpspace);
20 WDL_mergesort(b2, n2, size, compar, tmpspace);
26 if (compar(b1, b2) > 0) // out of order, go to full merge
28 size_t sofar = b1-(char*)base;
29 memcpy(tmpspace,base,sofar);
30 memcpy(tmpspace+sofar, b2, size);
31 b2 += size;
32 n2--;
34 char *writeptr=tmpspace+sofar+size;
35 while (n1 > 0 && n2 > 0)
37 if (compar(b1, b2) > 0)
39 memcpy(writeptr, b2, size);
40 b2 += size;
41 n2--;
43 else
45 memcpy(writeptr, b1, size);
46 b1 += size;
47 n1--;
49 writeptr += size;
52 if (n1 > 0) memcpy(writeptr, b1, n1 * size);
53 memcpy(base, tmpspace, (nmemb - n2) * size);
55 break;
58 // in order, just advance
59 b1 += size;
60 n1--;
62 while (n1 > 0 && n2 > 0);
65 #endif//_WDL_MERGESORT_H_