- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3-quick_sort.c
94 lines (83 loc) · 1.69 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
89
90
91
92
93
94
#include"sort.h"
/**
* quick_sort - Sorts an array of integers using the Quick Sort algorithm
*
* @array: array to be sorted
* @size: size of array
*/
voidquick_sort(int*array, size_tsize)
{
if (array==NULL||size<2)
return;
_quicksort(array, size, 0, size-1);
}
/**
* _quicksort - recursive function to sort the array using the quick sort
* algorithm
*
* @array: array to be sorted
* @low: first element of array
* @high: last element of array
* @size: size of array
*/
void_quicksort(int*array, size_tsize, intlow, inthigh)
{
intpivot_index;
if (low<0||low >= high)
return;
pivot_index=lomuto_partition(array, size, low, high);
_quicksort(array, size, low, pivot_index-1);
_quicksort(array, size, pivot_index+1, high);
}
/**
* lomuto_partition - divides the array into two partitions using the
* Lomuto partition scheme
*
* @array: array to be sorted
* @low: first element of array
* @high: last element of array
* @size: size of array
*
* Return: the pivot index
*/
intlomuto_partition(int*array, size_tsize, intlow, inthigh)
{
intpivot=array[high];
intpivot_index=low-1;
intj;
for (j=low; j <= high-1; j++)
{
if (array[j] <= pivot)
{
pivot_index++;
if (pivot_index!=j)
{
swap(&array[pivot_index], &array[j]);
print_array(array, size);
}
}
}
pivot_index++;
if (array[pivot_index] >pivot)
{
swap(&array[pivot_index], &array[high]);
print_array(array, size);
}
return (pivot_index);
}
/**
* swap - swaps two element in an array
* @x: the first value
* @y: the second value
*/
voidswap(int*x, int*y)
{
if (!x|| !y)
return;
if (*x!=*y)
{
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
}