-
Notifications
You must be signed in to change notification settings - Fork 0
/
3-quick_sort.c
77 lines (72 loc) · 1.36 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
#include "sort.h"
/**
* swap_elements - used to swap the elements in the array;
* @a: the first element;
* @b: the second element to be swapd with the other;
*
*
*/
void swap_elements(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
/**
* lomuto_partition - this partitions the function for quick sort
* @array: the array
* @low: the lower index
* @hi: the higher index to be partitioned
* @size: the size of the array
*
* Return: return value y
*/
int lomuto_partition(int *array, int low, int hi, size_t size)
{
int pivot = array[hi];
int x, y = (low - 1);
for (x = low; x <= hi; x++)
{
if (array[x] <= pivot)
{
y++;
if (y != x)
{
swap_elements(&array[y], &array[x]);
print_array(array, size);
}
}
}
return (y);
}
/**
* sort_lomuto - it sorts the array recursively
* @array: the array
* @low: the lowest value
* @hi: the highest value
* @size: the size of the array
*
*
*/
void sort_lomuto(int *array, int low, int hi, size_t size)
{
int x;
if (low < hi)
{
x = lomuto_partition(array, low, hi, size);
sort_lomuto(array, low, x - 1, size);
sort_lomuto(array, x + 1, hi, size);
}
}
/**
* quick_sort - quick Sort using lomuto partition
* @array: the array which will be sorted
* @size: the size of the array
*
*
*/
void quick_sort(int *array, size_t size)
{
sort_lomuto(array, 0, size - 1, size);
}