-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3-quick_sort.c
82 lines (71 loc) · 1.39 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
74
75
76
77
78
79
80
81
#include "sort.h"
/**
* swap - swaps 2 numbers
* @a: pointer to the first one
* @b: pointer to the second one
*/
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
/**
* partition - partition thr array using the
* lomuto partition scheme
* @array: the array
* @size: size of the array
* @lo: the first element
* @hi: the last element
*
* Return: index of the pivot
*/
int partition(int *array, size_t size, int lo, int hi)
{
int pivot = array[hi];
int i = lo - 1, j;
for (j = lo; j < hi; j++)
{
if (array[j] <= pivot)
{
i++;
swap(&array[i], &array[j]);
if (i != j)
print_array(array, size);
}
}
i++;
swap(&array[i], &array[hi]);
if (i != j)
print_array(array, size);
return (i);
}
/**
* my_quick_sort - my modification to be able to print the array
*
* @array: the array
* @size: the size
* @lo: the first element
* @hi: the last element
*/
void my_quick_sort(int *array, size_t size, int lo, int hi)
{
int p = 0;
if (lo >= hi || lo < 0 || array == NULL || size < 2)
return;
p = partition(array, size, lo, hi);
my_quick_sort(array, size, lo, p - 1);
my_quick_sort(array, size, p + 1, hi);
}
/**
* quick_sort - Sorts an array using the quick sort algorithm
*
* @array: The array to be sorted
* @size: The size of the array
*
* Return: void
*/
void quick_sort(int *array, size_t size)
{
my_quick_sort(array, size, 0, size - 1);
}