-
Notifications
You must be signed in to change notification settings - Fork 3
/
107-quick_sort_hoare.c
76 lines (70 loc) · 1.46 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
#include "sort.h"
#include <stdio.h>
#include <stdlib.h>
/**
* partition - finds the partition for the quicksort using the Hoare scheme
* @array: array to sort
* @lo: lowest index of the partition to sort
* @hi: highest index of the partition to sort
* @size: size of the array
*
* Return: index of the partition
*/
size_t partition(int *array, ssize_t lo, ssize_t hi, size_t size)
{
int swap, pivot;
pivot = array[hi];
while (lo <= hi)
{
while (array[lo] < pivot)
lo++;
while (array[hi] > pivot)
hi--;
if (lo <= hi)
{
if (lo != hi)
{
swap = array[lo];
array[lo] = array[hi];
array[hi] = swap;
print_array(array, size);
}
lo++;
hi--;
}
}
return (hi);
}
/**
* quicksort - sorts a partition of an array of integers
* @array: array to sort
* @lo: lowest index of the partition to sort
* @hi: highest index of the partition to sort
* @size: size of the array
*
* Return: void
*/
void quicksort(int *array, ssize_t lo, ssize_t hi, size_t size)
{
ssize_t pivot;
if (lo < hi)
{
pivot = partition(array, lo, hi, size);
quicksort(array, lo, pivot, size);
quicksort(array, pivot + 1, hi, size);
}
}
/**
* quick_sort_hoare - sorts an array of integers in ascending order using the
* Quick sort algorithm
* @array: The array to sort
* @size: The size of the array
*
* Return: void
*/
void quick_sort_hoare(int *array, size_t size)
{
if (array == NULL || size < 2)
return;
quicksort(array, 0, size - 1, size);
}