-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path3-quick_sort.c
101 lines (88 loc) · 1.57 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
95
96
97
98
99
100
101
#include "sort.h"
/**
* quick_sort - Function that sorts an array based on
* quick sort algorithm
* @array: Array to be sorted
* @size: Size of array
* Return: 0
*/
void quick_sort(int *array, size_t size)
{
size_t pivot;
if (!array || size < 2)
return;
print_sort(array, size, 1);
/* partition and get pivot index */
pivot = partition(array, size);
/* repeat for left of index */
quick_sort(array, pivot);
/* repeat for index and right */
quick_sort(array + pivot, size - pivot);
}
/**
* swap - Function that swaps two values
*
* @a: Fisrt value
* @b: Second value
* Return: 0
*/
void swap(int *a, int *b)
{
int tmp;
tmp = *b;
*b = *a;
*a = tmp;
}
/**
* partition - Function that sets the pivot for quick_sort
*
* @array: Array to partition
* @size: Size of array
* Return: (i + 1)
*/
size_t partition(int array[], size_t size)
{
int pivot;
size_t i = -1;
size_t j;
if (!array || size < 2)
return (0);
pivot = array[size - 1];
for (j = 0; j < size - 1; j++)
{
if (array[j] <= pivot)
{
i++;
if (i != j)
{
swap(&array[i], &array[j]);
print_sort(array, size, 0);
}
}
}
if (i + 1 != size - 1)
{
swap(&array[i + 1], &array[size - 1]);
print_sort(array, size, 0);
}
return (i + 1);
}
/**
* print_sort - Function that prints as it should
* @array: Array to be printed
* @size: Size of array
* @init: Should initialize array
* Return: 0
*/
void print_sort(int array[], size_t size, int init)
{
static int *p = (void *)0;
static size_t s;
if (!p && init)
{
p = array;
s = size;
}
if (!init)
print_array(p, s);
}