-
Notifications
You must be signed in to change notification settings - Fork 0
/
103-merge_sort.c
executable file
·102 lines (87 loc) · 2.14 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "sort.h"
/**
* mergeSort - sorts an array of integers in ascending order.
* @array: the array to be sorted
* @tmp_array: a temporary array used during the sorting process
* @start: the starting index of the sub-array to be sorted
* @end: the ending index of the sub-array to be sorted
* Return: void
*/
void mergeSort(int *array, int *tmp_array, size_t start, size_t end)
{
size_t mid;
if (start >= end)
return;
mid = start + (end - start) / 2;
/*Check if the first half is bigger and adjust the middle index*/
if ((mid - start + 1) > (end - mid))
mid--;
mergeSort(array, tmp_array, start, mid);
mergeSort(array, tmp_array, mid + 1, end);
/* print subarrays */
printf("Merging...\n");
printf("[left]: ");
print_array(array + start, mid - start + 1);
printf("[right]: ");
print_array(array + mid + 1, end - mid);
merge(array, tmp_array, start, mid, end);
printf("[Done]: ");
print_array(array + start, end - start + 1);
}
/**
* merge - merges two sorted sub-arrays into a single sorted sub-array
* @array: the array containing the two sub-arrays to be merged
* @tmp_array: a temporary array used during the sorting process
* @start: the starting index of the first sub-array
* @mid: the ending index of the first sub-array
* @end: the ending index of the second sub-array
* Return: void
*/
void merge(int *array, int *tmp_array, size_t start, size_t mid, size_t end)
{
size_t i, j, k;
i = start;
j = mid + 1;
k = start;
while (i <= mid && j <= end)
{
if (array[i] < array[j])
{
tmp_array[k++] = array[i++];
}
else
{
tmp_array[k++] = array[j++];
}
}
while (i <= mid)
{
tmp_array[k++] = array[i++];
}
while (j <= end)
{
tmp_array[k++] = array[j++];
}
for (i = start; i <= end; i++)
{
array[i] = tmp_array[i];
}
}
/**
* merge_sort - sorts an array using the Merge sort algorithm
* @array: the array to be sorted
* @size: the number of elements in the array
*
* Return: void
*/
void merge_sort(int *array, size_t size)
{
int *tmp_array;
if (array == NULL || size < 2)
return;
tmp_array = malloc(size * sizeof(int));
if (!tmp_array)
return;
mergeSort(array, tmp_array, 0, size - 1);
free(tmp_array);
}