-
Notifications
You must be signed in to change notification settings - Fork 2
/
internal_sort.c
64 lines (48 loc) · 1.48 KB
/
internal_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
/*
* Sort records in the memory buffer with internal mergeSort algorithm
* */
#include <stdlib.h>
#include <stdio.h>
#include "internal_sort.h"
void mergeSort(unsigned int *arr, int n) {
unsigned int *tmpArray;
tmpArray = malloc(n * sizeof(unsigned int));
if (tmpArray != NULL) {
mSort(arr, tmpArray, 0, n - 1);
free(tmpArray);
} else {
fprintf(stderr, "No space for tmp array!");
exit(0);
}
}
void mSort(unsigned int *arr, unsigned int *tmp, int left, int right) {
int center;
if (left < right) {
center = (left + right) / 2;
mSort(arr, tmp, left, center);
mSort(arr, tmp, center + 1, right);
merge(arr, tmp, left, center + 1, right);
}
}
void merge(unsigned int *arr, unsigned int *tmp, int lpos, int rpos, int rightend) {
int i, leftend, numElements, tmppos;
leftend = rpos - 1;
tmppos = lpos;
numElements = rightend - lpos + 1;
//main loop
while(lpos <= leftend && rpos <= rightend) {
if (arr[lpos] <= arr[rpos]) {
tmp[tmppos++] = arr[lpos++];
} else {
tmp[tmppos++] = arr[rpos++];
}
}
while (lpos <= leftend) // copy rest of first half
tmp[tmppos++] = arr[lpos++];
while (rpos <= rightend) // copy rest of second half
tmp[tmppos++] = arr[rpos++];
// copy tmp array back
for (i = 0; i < numElements; i++, rightend--) {
arr[rightend] = tmp[rightend];
}
}