-
Notifications
You must be signed in to change notification settings - Fork 0
/
3-quick_sort.c
92 lines (79 loc) · 1.67 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
#include "sort.h"
/**
* quick_sort - Sorts an array of integers in ascending order using
* the Quick sort algorithm
* @array: The array to be sorted
* @size: The size of the array
* Return: Nothing
*/
void quick_sort(int *array, size_t size)
{
if (size < 2)
return;
_qsort(array, 0, size - 1, size);
}
/**
* _qsort - Sort the array recursively
* @array: The array to be sorted
* @lb: The lower bound of the index
* @ub: The upper bound of the index
* @size: The size of the array
* Return: Nothing
*/
void _qsort(int *array, ssize_t lb, ssize_t ub, size_t size)
{
size_t p; /* piovt index */
if (lb >= ub)
return;
p = partition(array, lb, ub, size);
_qsort(array, lb, p - 1, size);
_qsort(array, p + 1, ub, size);
}
/**
* partition - Partition the array into two part
* @array: The array to be partition
* @lb: The lower bound of the index
* @ub: The upper bound of the index
* @size: The size of the array
* Return: The right index of the pivot element
*/
size_t partition(int *array, size_t lb, size_t ub, size_t size)
{
int pivot;
size_t i, j;
int fswap;
pivot = array[ub];
i = lb - 1; /* temporary pivot index */
fswap = 0;
for (j = lb; j < ub; j++)
{
if (array[j] <= pivot)
{
i++;
swap(&array[i], &array[j]);
if (array[i] != array[j] || i != j)
{
print_array(array, size);
fswap = 1;
}
}
}
i++;
swap(&array[i], &array[ub]);
if (fswap || i != ub)
print_array(array, size);
return (i); /* index of the pivot elemenet */
}
/**
* swap - Swaps the position of two numbers
* @a: The first integer
* @b: The second integer
* Return: Nothing
*/
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}