-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSortv2.c
63 lines (57 loc) · 1.32 KB
/
MergeSortv2.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
/**
* Implement mergesort algorithm from Intro to Design & Analysis of Algorithm 3e
* Second implementation with better memory management
* Inspired by http://vinayakgarg.wordpress.com/2012/11/08/merge-sort-program-in-c/
*/
#include <stdlib.h>
#include <stdio.h>
void mergeSort(int *, int, int);
void merge(int * , int, int, int);
int main() {
int testArray[10] = {10, 5, 9, 2, 0, 6, 7, 4, 8, 3};
int i;
for (i = 0; i < 10; i++) printf("%d ", testArray[i]);
printf(" test array \n");
mergeSort(testArray, 0, 9);
for (i = 0; i < 10; i++) {
printf("%d ", testArray[i]);
}
printf("\n");
}
void mergeSort(int * a, int left, int right) {
int len = right - left + 1;
int mid = (right + left) / 2;
if (len > 1) {
mergeSort(a, left, mid);
mergeSort(a, mid + 1, right);
merge(a, left, mid, right);
}
}
void merge(int * a, int left, int mid, int right) {
int * temp = (int *) malloc(sizeof(int) * (right - left + 1));
int i = left, j = mid + 1, k = 0;
while (i <= mid && j <= right) {
if (a[i] <= a[j]) {
temp[k] = a[i];
i++;
} else {
temp[k] = a[j];
j++;
}
k++;
}
while (i <= mid) {
temp[k] = a[i];
i++; k++;
}
while (j <= right) {
temp[k] = a[j];
j++; k++;
}
k--;
while(k >= 0) {
a[left + k] = temp[k];
k--;
}
free(temp);
}