-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path103-merge_sort.c
89 lines (83 loc) · 1.95 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
#include "sort.h"
#include <stdlib.h>
#include <stdio.h>
/**
* TDMerge - sorts and merges the sub arrays in source
* @start: starting index (inclusive) for the left sub array
* @middle: end index (exclusive) for the left sub array and
* starting index (inclusive) for the right sub array
* @end: end index (exclusive) for the right sub array
* @dest: destination for data
* @source: source of data
*
* Return: void
*/
void TDMerge(size_t start, size_t middle, size_t end, int *dest, int *source)
{
size_t i, j, k;
printf("Merging...\n");
printf("[left]: ");
print_array(source + start, middle - start);
printf("[right]: ");
print_array(source + middle, end - middle);
i = start;
j = middle;
for (k = start; k < end; k++)
{
if (i < middle && (j >= end || source[i] <= source[j]))
{
dest[k] = source[i];
i++;
}
else
{
dest[k] = source[j];
j++;
}
}
printf("[Done]: ");
print_array(dest + start, end - start);
}
/**
* TDSplitMerge - recursively splits the array and merges the sorted arrays
* @start: starting index (inclusive)
* @end: end index (exclusive)
* @array: the array to sort
* @copy: a copy of the array
*
* Return: void
*/
void TDSplitMerge(size_t start, size_t end, int *array, int *copy)
{
size_t middle;
if (end - start < 2)
return;
middle = (start + end) / 2;
TDSplitMerge(start, middle, array, copy);
TDSplitMerge(middle, end, array, copy);
TDMerge(start, middle, end, array, copy);
for (middle = start; middle < end; middle++)
copy[middle] = array[middle];
}
/**
* merge_sort - sorts an array of integers in ascending order using the
* Merge sort algorithm
* @array: array to sort
* @size: size of the array
*
* Return: void
*/
void merge_sort(int *array, size_t size)
{
size_t i;
int *copy;
if (array == NULL || size < 2)
return;
copy = malloc(sizeof(int) * size);
if (copy == NULL)
return;
for (i = 0; i < size; i++)
copy[i] = array[i];
TDSplitMerge(0, size, array, copy);
free(copy);
}