-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path103-merge_sort.c
83 lines (73 loc) · 1.56 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
80
81
82
83
#include "sort.h"
/**
* merge_compare - compares merges
* @array: the integer array to sort
* @start: the start index
* @stop: the stop index
* @new: the output array
*
* Return: void.
*/
void merge_compare(int *array, size_t start, size_t stop, int *new)
{
size_t i = start, j, k, mid;
j = mid = (start + stop) / 2;
printf("Merging...\n");
printf("[left]: ");
print_array(array + start, mid - start);
printf("[right]: ");
print_array(array + mid, stop - mid);
for (k = start; k < stop; k++)
if (i < mid && (j >= stop || array[i] <= array[j]))
{
new[k] = array[i++];
}
else
{
new[k] = array[j++];
}
printf("[Done]: ");
print_array(new + start, stop - start);
}
/**
* merge_sort_top_down - sorts top-down recursively
* @array: the integer array to sort
* @start: the start index
* @stop: the stop index
* @new: the output array
*
* Return: void.
*/
void merge_sort_top_down(int *array, size_t start, size_t stop, int *new)
{
size_t mid;
mid = (start + stop) / 2;
if (stop - start < 2)
{
return;
}
merge_sort_top_down(new, start, mid, array);
merge_sort_top_down(new, mid, stop, array);
merge_compare(array, start, stop, new);
}
/**
* merge_sort - sorts by merge sort algorithm
* @array: the integer array to sort
* @size: the size of the array
*
* Return: void.
*/
void merge_sort(int *array, size_t size)
{
int *new;
size_t i;
if (!array || size < 2)
return;
new = malloc(sizeof(int) * size);
if (!new)
return;
for (i = 0; i < size; i++)
new[i] = array[i];
merge_sort_top_down(new, 0, size, array);
free(new);
}