-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3-quick_sort.c
79 lines (72 loc) · 1.59 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
#include "sort.h"
int lomutoPartition(int *array, int low, int high, size_t size);
void lomutoSort(int *array, int start, int end, size_t size);
/**
* quick_sort - Sorts an array of integers in ascending order,
* using the Quick sort algorithm.
*
* @array: The array to be arranged.
* @size: Size of the array.
*/
void quick_sort(int *array, size_t size)
{
if (size < 2)
return;
lomutoSort(array, 0, size - 1, size);
}
/**
* lomutoPartition - array partition
*
* @array: array to sort
* @low: first position
* @high: last position
* @size: array size
*
* Return: int pivot index
*/
int lomutoPartition(int *array, int low, int high, size_t size)
{
int pivot, index, forIndex, temp;
pivot = array[high];
index = low - 1;
for (forIndex = low; forIndex < high; forIndex++)
{
if (pivot >= array[forIndex])
{
index += 1;
if (index < forIndex)
{
temp = array[index];
array[index] = array[forIndex];
array[forIndex] = temp;
print_array(array, size);
}
}
}
if (array[index + 1] > pivot)
{
temp = array[index + 1];
array[index + 1] = array[high];
array[high] = temp;
print_array(array, size);
}
return (index + 1);
}
/**
* lomutoSort - sorts an array of integers recursively
*
* @array: array to sort
* @start: first position
* @end: last position
* @size: array size
*/
void lomutoSort(int *array, int start, int end, size_t size)
{
int partition_index;
if (start < end)
{
partition_index = lomutoPartition(array, start, end, size);
lomutoSort(array, start, partition_index - 1, size);
lomutoSort(array, partition_index + 1, end, size);
}
}