forked from Obelem/sorting_algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path3-quick_sort.c
73 lines (67 loc) · 1.22 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
68
69
70
71
72
73
#include "sort.h"
/**
* quick_sort - function that sorts an array of integers
* in ascending order using the Quick sort algorithm
* @array: array
* @size: array's size
* Return: void
*/
void quick_sort(int *array, size_t size)
{
if (array == NULL || size < 2)
return;
quick_s(array, 0, size - 1, size);
}
/**
* partition - partition
* @array: array
* @lo: lower
* @hi: higher
* @size: array's size
* Return: i
*/
int partition(int *array, int lo, int hi, size_t size)
{
int i = lo - 1, j = lo;
int pivot = array[hi], aux = 0;
for (; j < hi; j++)
{
if (array[j] < pivot)
{
i++;
if (array[i] != array[j])
{
aux = array[i];
array[i] = array[j];
array[j] = aux;
print_array(array, size);
}
}
}
if (array[i + 1] != array[hi])
{
aux = array[i + 1];
array[i + 1] = array[hi];
array[hi] = aux;
print_array(array, size);
}
return (i + 1);
}
/**
* quick_s - quick sort
* @array: given array
* @lo: lower
* @hi:higher
* @size: array's size
* Return: void
*/
void quick_s(int *array, int lo, int hi, size_t size)
{
int pivot;
if (lo < hi)
{
pivot = partition(array, lo, hi, size);
quick_s(array, lo, pivot - 1, size);
quick_s(array, pivot + 1, hi, size);
}
}