-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path103-merge_sort.c
executable file
·79 lines (74 loc) · 1.5 KB
/
103-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
#include "sort.h"
/**
* prints - prints left, right, and merged halves
* @arr: original or tmp array
* @side: left, right, or merged half
* @start: starting index
* @end: ending index
*/
void prints(int *arr, char *side, size_t start, size_t end)
{
size_t i;
printf("[%s]: ", side);
for (i = start; i < end; i++)
{
if (i != (end - 1))
printf("%d, ", arr[i]);
else
printf("%d\n", arr[i]);
}
}
/**
* rec_merge - recursively splits and merges halves
* @array: original array
* @sortArr: tmp array to hold sorted elements
* @l: starting index
* @r: ending index
*/
void rec_merge(int *array, int *sortArr, size_t l, size_t r)
{
size_t i, l_half, r_half;
size_t mid = (l + r) / 2;
if (r - l <= 1)
return;
rec_merge(array, sortArr, l, mid);
rec_merge(array, sortArr, mid, r);
printf("Merging...\n");
prints(array, "left", l, mid);
prints(array, "right", mid, r);
l_half = l;
r_half = mid;
for (i = l; i < r; i++)
{
if ((l_half < mid) &&
((r_half == r) || (array[l_half] < array[r_half])))
{
sortArr[i] = array[l_half];
l_half++;
}
else
{
sortArr[i] = array[r_half];
r_half++;
}
}
prints(sortArr, "Done", l, r);
for (i = l; i < r; i++)
array[i] = sortArr[i];
}
/**
* merge_sort - sorts mergly
* @array: array sort
* @size: size of array
*/
void merge_sort(int *array, size_t size)
{
int *sortArr;
if (!(array) || size < 2)
return;
sortArr = malloc(sizeof(int) * size);
if (!(sortArr))
return;
rec_merge(array, sortArr, 0, size);
free(sortArr);
}