-
Notifications
You must be signed in to change notification settings - Fork 0
/
3-quick_sort.c
67 lines (61 loc) · 1.26 KB
/
3-quick_sort.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
#include "sort.h"
/**
* partition - Lomuto partition scheme
* @array: array to sort
* @low: low index
* @high: high index
* @size: size of the array
* Return: index of the pivot
*/
int partition(int *array, int low, int high, size_t size)
{
int pivot = array[high], i = low - 1, tmp;
int j = low;
while (j < high)
{
if (array[j] <= pivot)
{
i++;
tmp = array[i];
array[i] = array[j];
array[j] = tmp;
if (i != j)
print_array(array, size);
}
j++;
}
tmp = array[i + 1];
array[i + 1] = array[high];
array[high] = tmp;
if (i + 1 != j)
print_array(array, size);
return (i + 1);
}
/**
* quicksort - helper function for quick_sort
* @array: array to sort
* @low: low index
* @high: high index
* @size: size of the array
*/
void quicksort(int *array, int low, int high, size_t size)
{
if (low < high)
{
int pivot_index = partition(array, low, high, size);
quicksort(array, low, pivot_index - 1, size);
quicksort(array, pivot_index + 1, high, size);
}
}
/**
* quick_sort - sorts an array of integers in ascending order
* using the Quick sort algorithm
* @array: array to sort
* @size: size of the array
*/
void quick_sort(int *array, size_t size)
{
if (array == NULL || size <= 1)
return;
quicksort(array, 0, size - 1, size);
}