-
Notifications
You must be signed in to change notification settings - Fork 0
/
103-merge_sort.c
82 lines (69 loc) · 2.1 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
#include "sort.h"
void merge_subarr(int *subarr, int *buff, size_t front, size_t mid,
size_t back);
void merge_sort_recursive(int *subarr, int *buff, size_t front, size_t back);
void merge_sort(int *array, size_t size);
/**
* merge_subarr - Sort a subarray of integers.
* @subarr: A subarray of an array of integers to sort.
* @buff: A buffer to store the sorted subarray.
* @front: The front index of the array.
* @mid: The middle index of the array.
* @back: The back index of the array.
*/
void merge_subarr(int *subarr, int *buff, size_t front, size_t mid,
size_t back)
{
size_t i, j, k = 0;
printf("Merging...\n[left]: ");
print_array(subarr + front, mid - front);
printf("[right]: ");
print_array(subarr + mid, back - mid);
for (i = front, j = mid; i < mid && j < back; k++)
buff[k] = (subarr[i] < subarr[j]) ? subarr[i++] : subarr[j++];
for (; i < mid; i++)
buff[k++] = subarr[i];
for (; j < back; j++)
buff[k++] = subarr[j];
for (i = front, k = 0; i < back; i++)
subarr[i] = buff[k++];
printf("[Done]: ");
print_array(subarr + front, back - front);
}
/**
* merge_sort_recursive - Implement the merge sort algorithm through recursion.
* @subarr: A subarray of an array of integers to sort.
* @buff: A buffer to store the sorted result.
* @front: The front index of the subarray.
* @back: The back index of the subarray.
*/
void merge_sort_recursive(int *subarr, int *buff, size_t front, size_t back)
{
size_t mid;
if (back - front > 1)
{
mid = front + (back - front) / 2;
merge_sort_recursive(subarr, buff, front, mid);
merge_sort_recursive(subarr, buff, mid, back);
merge_subarr(subarr, buff, front, mid, back);
}
}
/**
* merge_sort - Sort an array of integers in ascending
* order using the merge sort algorithm.
* @array: An array of integers.
* @size: The size of the array.
*
* Description: Implements the top-down merge sort algorithm.
*/
void merge_sort(int *array, size_t size)
{
int *buff;
if (array == NULL || size < 2)
return;
buff = malloc(sizeof(int) * size);
if (buff == NULL)
return;
merge_sort_recursive(array, buff, 0, size);
free(buff);
}