-
Notifications
You must be signed in to change notification settings - Fork 5
/
merge_sort.c
93 lines (73 loc) · 1.67 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void merge(int *, int, int);
/**
* Merge sort algorithm.
*
* @param int input Array to sort
* @param int n Number of data in search array
*
* @return void
*/
void merge_sort(int *data, int start, int end)
{
if (start == end) {
return;
}
int mid = (start + end) / 2;
if (start < end) {
merge_sort(data, start, mid);
merge_sort(data, mid + 1, end);
merge(data, start, end);
}
}
/**
* Merge two sub arrays.
*
* @param int data Array
* @param int start Start index of an array
* @param int end End index of an array
*
* @return void
*/
void merge(int *data, int start, int end)
{
int mid = (start + end) / 2;
int i = start, j = mid + 1, k = 0;
int *temp = (int *) malloc((end - start) * sizeof(int));
while (i <= mid && j <= end) {
if (*(data + i) < *(data + j)) {
temp[k++] = data[i++];
} else {
temp[k++] = data[j++];
}
}
//leftovers from left sub array
while (i <= mid) {
temp[k++] = data[i++];
}
//leftovers from right sub array
while (j <= end) {
temp[k++] = data[j++];
}
//copy items to original array
memcpy(data + start, temp, (end - start + 1) * sizeof(int));
free(temp);
}
int main()
{
int n;
printf("How many numbers? ");
scanf("%d", &n);
int *input = (int *) malloc(n * sizeof(int));
printf("Enter %d numbers: ", n);
for (int i = 0; i < n; i++) {
scanf("%d", &input[i]);
}
merge_sort(input, 0, n - 1);
for (int i = 0; i < n; i++) {
printf("%d\t", *(input + i));
}
free(input);
}