-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path107-quick_sort_hoare.c
executable file
·99 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
96
97
98
99
#include "sort.h"
void swapping_ints(int *a, int *b);
int hoare_partitioning(int *array, size_t size, int left, int right);
void hoare_sorting(int *array, size_t size, int left, int right);
void quick_sort_hoare(int *array, size_t size);
/**
* swapping_ints - Swapping two integers in an array
* @a: First integer to be swapped
* @b: Second integer to be swapped
*/
void swapping_ints(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
/**
* hoare_partitioning - Order a subset of an array of integers
* according to the Hoare partition scheme.
* @array: Array of integers
* @size: Array size
* @left: Starting index of the subset to order
* @right: Ending index of the subset to order
*
* Return: Final partitioned index
*
* Description: Using the last element of the partition as the pivot.
* Prints the array after every swap of two elements
*/
int hoare_partitioning(int *array, size_t size, int left, int right)
{
int pivot, top, bottom;
pivot = array[right];
for (top = left - 1, bottom = right + 1; top < bottom;)
{
do {
top++;
} while (array[top] < pivot);
do {
bottom--;
} while (array[bottom] > pivot);
if (top < bottom)
{
swapping_ints(array + top, array + bottom);
print_array(array, size);
}
}
return (top);
}
/**
* hoare_sorting - Implementing the Quick sort algorithm through recursion
* @array: Array of integers to be sorted
* @size: Array size
* @left: Starting index of the array partition to order.
* @right: Ending index of the array partition to order.
*
* Description: Using the Hoare partitioning scheme
*/
void hoare_sorting(int *array, size_t size, int left, int right)
{
int piece;
if (right - left > 0)
{
piece = hoare_partitioning(array, size, left, right);
hoare_sorting(array, size, left, piece - 1);
hoare_sorting(array, size, piece, right);
}
}
/**
* quick_sort_hoare - Sorting an array of integers in ascending
* order using the Quick sort algorithm
* @array: Array of integers
* @size: Array size
*
* Description: Using the Hoare partitioning scheme
* Printing the array after every swap of two elements
*/
void quick_sort_hoare(int *array, size_t size)
{
if (array == NULL || size < 2)
return;
hoare_sorting(array, size, 0, size - 1);
}