-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path107-quick_sort_hoare.c
executable file
·83 lines (77 loc) · 1.58 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include "sort.h"
/**
* swap - swaps 2 int values
* @array: the integer array to sort
* @size: the size of the array
* @a: address of first value
* @b: address of second value
*
* Return: void
*/
void swap(int *array, size_t size, int *a, int *b)
{
if (*a != *b)
{
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}
print_array((const int *)array, size);
}
/**
* hoare_partition - partitions the array
* @array: the integer array to sort
* @size: the size of the array
* @lo: the low index of the sort range
* @hi: the high index of the sort range
*
* Return: void
*/
size_t hoare_partition(int *array, ssize_t size, ssize_t lo, ssize_t hi)
{
ssize_t i = lo - 1, j = hi + 1;
int pivot = array[hi];
while (i < size)
{
while (array[++i] < pivot)
;
while (array[--j] > pivot)
;
if (i < j)
swap(array, size, &array[i], &array[j]);
else if (i >= j)
break;
}
return (i);
}
/**
* quicksort - quicksorts via hoare partitioning scheme
* @array: the integer array to sort
* @size: the size of the array
* @lo: the low index of the sort range
* @hi: the high index of the sort range
*
* Return: void
*/
void quicksort(int *array, size_t size, ssize_t lo, ssize_t hi)
{
if (lo < hi)
{
size_t p = hoare_partition(array, size, lo, hi);
quicksort(array, size, lo, p - 1);
quicksort(array, size, p, hi);
}
}
/**
* quick_sort_hoare - calls quicksort
* @array: the integer array to sort
* @size: the size of the array
*
* Return: void
*/
void quick_sort_hoare(int *array, size_t size)
{
if (!array || size < 2)
return;
quicksort(array, size, 0, size - 1);
}