-
Notifications
You must be signed in to change notification settings - Fork 0
/
3-quick_sort.c
88 lines (77 loc) · 1.58 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
82
83
84
85
86
87
88
#include "sort.h"
/**
* swap_array - Swap two integers in an array.
* @a: first integer to swap
* @b: second integer to swap
*/
void swap_array(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
/**
* partition - Sort a subset of an array of integers
*
* @array: array of integers
* @size: size of the array
* @low: begining index of the subset to sort
* @high: last index of the subset to sort
*
* Return: pivot index
*/
int partition(int *array, size_t size, int low, int high)
{
int *pivot, above, below;
pivot = array + high;
for (above = below = low; below < high; below++)
{
if (array[below] < *pivot)
{
if (above < below)
{
swap_array(array + below, array + above);
print_array(array, size);
}
above++;
}
}
if (array[above] > *pivot)
{
swap_array(array + above, pivot);
print_array(array, size);
}
return (above);
}
/**
* sort - Implement the quicksort algorithm (lomuto)
*
* @array: An array of integers to sort
* @size: The size of the array
* @low: begining index of the array partition to sort
* @high: last index of the array partition to sort
*
*/
void sort(int *array, size_t size, int low, int high)
{
int split;
if (high - low > 0)
{
split = partition(array, size, low, high);
sort(array, size, low, split - 1);
sort(array, size, split, high);
}
}
/**
* quick_sort - Sorts an array of integers using Lomuto
*
* @array: A pointer to an array of integers
* @size: Size of the array
*/
void quick_sort(int *array, size_t size)
{
if (array == NULL || size < 2)
return;
sort(array, size, 0, size - 1);
}