-
Notifications
You must be signed in to change notification settings - Fork 1
/
107-quick_sort_hoare.c
68 lines (61 loc) · 1.32 KB
/
107-quick_sort_hoare.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
#include "sort.h"
/**
* quick_sort_hoare - Function that sorts ints w/ quick sort algorithm
* @array: The array of integers
* @size: The array size
*
* Return: None
*/
void quick_sort_hoare(int *array, size_t size)
{
if (array == NULL || size < 2)
return;
hoare_sort(array, size, 0, size - 1);
}
/**
* hoare_sort - Function that uses quicksort algorithm through recursion
* @array: The array of integers
* @size: The array size
* @left: The starting index of the array partition to order
* @right: The ending index of the array partition to order
*
* Return: None
*/
void hoare_sort(int *array, size_t size, int left, int right)
{
int pivot, above, below;
if (right - left > 0)
{
pivot = array[right];
for (above = left - 1, below = right + 1; above < below;)
{
do {
above++;
} while (array[above] < pivot);
do {
below--;
} while (array[below] > pivot);
if (above < below)
{
swap(array + above, array + below);
print_array(array, size);
}
}
hoare_sort(array, size, left, above - 1);
hoare_sort(array, size, above, right);
}
}
/**
* swap - Function to swap position of 2 elements in list
* @first: Fist element
* @second: Second element
*
* Return: None
*/
void swap(int *first, int *second)
{
int tmp_elem;
tmp_elem = *first;
*first = *second;
*second = tmp_elem;
}