-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmergesort.c
64 lines (60 loc) · 1.92 KB
/
mergesort.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
#include "mergesort.h"
void merge_sort(data array[], int len) {
if (len > 1) {
int middle = len/2; // split the array
merge_sort(array, middle); // order from 0 to middle-1
merge_sort(array+middle, len-middle); // order from middle to len-1
merge(array, middle, len); // merge the two arrays
}
}
void merge_sort_debug(data array[], int len, STAT *stat) {
if (len > 1) {
int middle = len/2; // split the array
merge_sort_debug(array, middle, stat); // order from 0 to middle-1
merge_sort_debug(array+middle, len-middle, stat); // order from middle to len-1
stat->recc += 2;
merge_debug(array, middle, len, stat); // merge the two arrays
}
}
void merge(data array[], int sep, int end) { // merges arrays from 0 to sep-1 and from sep to end-1 (sep is the separation between the two arrays)
int i = 0, j = sep; // i scans from 0, j scans from j
data buff[end]; // buff is used to store data to avoid overwriting
int b = 0;
while (i < sep && j < end) {
if (array[i] < array[j])
buff[b++] = array[i++];
else
buff[b++] = array[j++];
}
while (i < sep) // complete the buff
buff[b++] = array[i++];
while (b-- > 0) // copy the buff on the array
array[b] = buff[b];
}
void merge_debug(data array[], int sep, int end, STAT *stat) { // merges arrays from 0 to sep-1 and from sep to end-1 (sep is the separation between the two arrays)
int i = 0, j = sep; // i scans from 0, j scans from j
data buff[end]; // buff is used to store data to avoid overwriting
if (stat->space < end) // update additional space usage
stat->space = end;
stat->allo += end;
int b = 0;
while (i < sep && j < end) {
if (array[i] < array[j]) {
buff[b++] = array[i++];
stat->write++;
}
else {
buff[b++] = array[j++];
stat->write++;
}
stat->comp++;
}
while (i < sep) { // complete the buff
buff[b++] = array[i++];
stat->write++;
}
while (b-- > 0) { // copy the buff on the array
array[b] = buff[b];
stat->write++;
}
}