-
Notifications
You must be signed in to change notification settings - Fork 1
/
3-quick_sort.c
74 lines (66 loc) · 1.34 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
#include "sort.h"
/**
* quick_sort - Function that sorts array of int w/ quicksort algorithm
* @array: THe integer array
* @size: Array size
*
* Return: None
*/
void quick_sort(int *array, size_t size)
{
if (array == NULL || size < 2)
return;
lomuto_sort(array, size, 0, size - 1);
}
/**
* lomuto_sort - Lomuto partition scheme
* @array: THe arrayof integers
* @size: Array size
* @left: The starting index of the array partition to order
* @right: The ending index of the array partition to order
*
* Return: None
*/
void lomuto_sort(int *array, size_t size, int left, int right)
{
int *pivot, above, below;
int part;
if (right - left > 0)
{
pivot = array + right;
for (above = below = left; below < right; below++)
{
if (array[below] < *pivot)
{
if (above < below)
{
swap(array + below, array + above);
print_array(array, size);
}
above++;
}
}
if (array[above] > *pivot)
{
swap(array + above, pivot);
print_array(array, size);
}
part = above;
lomuto_sort(array, size, left, part - 1);
lomuto_sort(array, size, part + 1, right);
}
}
/**
* swap - Function to swap position of 2 elements in list
* @first: Fist element
* @second: Second element
*
* Return: None
*/
void swap(int *first, int *second)
{
int tmp_elem;
tmp_elem = *first;
*first = *second;
*second = tmp_elem;
}