-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy path107-quick_sort_hoare.c
72 lines (68 loc) · 1.45 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
#include "sort.h"
/**
*swap - the positions of two elements into an array
*@array: array
*@item1: array element
*@item2: array element
*/
void swap(int *array, ssize_t item1, ssize_t item2)
{
int tmp;
tmp = array[item1];
array[item1] = array[item2];
array[item2] = tmp;
}
/**
*hoare_partition - hoare partition sorting scheme implementation
*@array: array
*@first: first array element
*@last: last array element
*@size: size array
*Return: return the position of the last element sorted
*/
int hoare_partition(int *array, int first, int last, int size)
{
int current = first - 1, finder = last + 1;
int pivot = array[last];
while (1)
{
do {
current++;
} while (array[current] < pivot);
do {
finder--;
} while (array[finder] > pivot);
if (current >= finder)
return (current);
swap(array, current, finder);
print_array(array, size);
}
}
/**
*qs - qucksort algorithm implementation
*@array: array
*@first: first array element
*@last: last array element
*@size: array size
*/
void qs(int *array, ssize_t first, ssize_t last, int size)
{
ssize_t position = 0;
if (first < last)
{
position = hoare_partition(array, first, last, size);
qs(array, first, position - 1, size);
qs(array, position, last, size);
}
}
/**
*quick_sort_hoare - prepare the terrain to quicksort algorithm
*@array: array
*@size: array size
*/
void quick_sort_hoare(int *array, size_t size)
{
if (!array || size < 2)
return;
qs(array, 0, size - 1, size);
}