-
Notifications
You must be signed in to change notification settings - Fork 0
/
3-quick_sort.c
81 lines (74 loc) · 1.49 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 - swap two elements of the array
* @array: array to swap its elements
* @x: first element
* @y: second element
* Return: Nothing
*/
void swap(int *array, int x, int y)
{
int temp;
temp = array[x];
array[x] = array[y];
array[y] = temp;
}
/**
* lomuto - uses lomuto partition scheme to divide the array
* @array: array to be sorted
* @low: lower bound of the array
* @up: upper bound of the array
* @size: size of the array
* Return: Nothing
*/
int lomuto(int *array, int low, int up, size_t size)
{
int pivot = array[up], i, j = low;
for (i = low; i < up; i++)
{
if (array[i] < pivot)
{
if (j < i)
{
swap(array, i, j);
print_array(array, size);
}
j++;
}
}
if (array[j] > pivot)
{
swap(array, up, j);
print_array(array, size);
}
return (j);
}
/**
* sorting - sort the partitioned parts of the array
* @array: array to be sorted
* @low: lower bound of the array
* @up: upper bound of the array
* @size: size of the array
* Return: Nothing
*/
void sorting(int *array, int low, int up, size_t size)
{
int p;
if (low >= up || low < 0)
return;
p = lomuto(array, low, up, size);
sorting(array, low, p - 1, size);
sorting(array, p + 1, up, size);
}
/**
* quick_sort - sorts an array of integers using the Quick sort algorithm
* @array: array to be sorted
* @size: size of the array
* Return: Nothing
*/
void quick_sort(int *array, size_t size)
{
if (size < 2 || array == NULL)
return;
sorting(array, 0, size - 1, size);
}