-
Notifications
You must be signed in to change notification settings - Fork 0
/
107-quick_sort_hoare.c
executable file
·95 lines (84 loc) · 2.26 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
84
85
86
87
88
89
90
91
92
93
94
95
#include "sort.h"
void swap_ints(int *a, int *b);
int hoare_partition(int *array, size_t size, int left, int right);
void hoare_sort(int *array, size_t size, int left, int right);
void quick_sort_hoare(int *array, size_t size);
/**
* swap_ints - Swap two integers in an array.
* @a: The first integer to swap.
* @b: The second integer to swap.
*/
void swap_ints(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
/**
* hoare_partition - Order a subset of an array of integers
* according to the hoare partition scheme.
* @array: The array of integers.
* @size: The size of the array.
* @left: The starting index of the subset to order.
* @right: The ending index of the subset to order.
*
* Return: The final partition index.
*
* Description: Uses the last element of the partition as the pivot.
* Prints the array after each swap of two elements.
*/
int hoare_partition(int *array, size_t size, int left, int right)
{
int pivot, above, below;
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_ints(array + above, array + below);
print_array(array, size);
}
}
return (above);
}
/**
* hoare_sort - Implement the quicksort algorithm through recursion.
* @array: An array of integers to sort.
* @size: The size of the array.
* @left: The starting index of the array partition to order.
* @right: The ending index of the array partition to order.
*
* Description: Uses the Hoare partition scheme.
*/
void hoare_sort(int *array, size_t size, int left, int right)
{
int part;
if (right - left > 0)
{
part = hoare_partition(array, size, left, right);
hoare_sort(array, size, left, part - 1);
hoare_sort(array, size, part, right);
}
}
/**
* quick_sort_hoare - Sort an array of integers in ascending
* order using the quicksort algorithm.
* @array: An array of integers.
* @size: The size of the array.
*
* Description: Uses the Hoare partition scheme. Prints
* the array after each swap of two elements.
*/
void quick_sort_hoare(int *array, size_t size)
{
if (array == NULL || size < 2)
return;
hoare_sort(array, size, 0, size - 1);
}