-
Notifications
You must be signed in to change notification settings - Fork 3
/
3-quick_sort.c
82 lines (73 loc) · 1.61 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 values of start and next index.
* @array: the array to work in.
* @size: size of array.
* @low: left most value
* @high: right most value
* Return: nothing.
*/
void swap(int *array, size_t size, int low, int high)
{
int temp;
if (array[low] != array[high])
{
temp = array[low];
array[low] = array[high];
array[high] = temp;
print_array(array, size);
}
}
/**
* partition - using Lomuto partition scheme for quicksort
* @array: pointer to array
* @size: size of array
* @low: left most value
* @high: right most value
* Return: pivot value
*/
int partition(int *array, size_t size, int low, int high)
{
int pivot_value = array[high];
int i = low - 1, j;
for (j = low; j <= high; j++)
{
if (array[j] < pivot_value)
{
i++;
swap(array, size, i, j);
}
}
swap(array, size, i + 1, high);
return (i + 1);
}
/**
* quicksort_recursion - recursive funtion for quicksort
* @array: pointer to array
* @size: size of array
* @low: lowest value
* @high: highest value
*/
void quicksort_recursion(int *array, size_t size, int low, int high)
{
int pivot_index;
if (low < high)
{
pivot_index = partition(array, size, low, high);
quicksort_recursion(array, size, low, pivot_index - 1);
quicksort_recursion(array, size, pivot_index + 1, high);
}
}
/**
* quick_sort - sorts an array of integers in ascending order
* using the Quick sort algorithm
* @array: the array to sort.
* @size: size of the array.
* Return: nothing.
*/
void quick_sort(int *array, size_t size)
{
if (!array || size < 2)
return;
quicksort_recursion(array, size, 0, size - 1);
}