forked from dayoonasanya/sorting_algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3-quick_sort.c
106 lines (85 loc) · 1.29 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
102
103
104
105
106
#include "sort.h"
/**
* quick_sort - array
*
* @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);
pivot = partition(array, size);
quick_sort(array, pivot);
quick_sort(array + pivot, size - pivot);
}
/**
* swap_func - swap.
*
* @a: a
* @b: b
* Return: 0
*/
void swap_func(int *a, int *b)
{
int tmp;
tmp = *b;
*b = *a;
*a = tmp;
}
/**
* partition - set pivot
*
* @array: array
* @size: size
* Return: incrimental
*/
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_func(&array[i], &array[j]);
print_sort(array, size, 0);
}
}
}
if (i + 1 != size - 1)
{
swap_func(&array[i + 1], &array[size - 1]);
print_sort(array, size, 0);
}
return (i + 1);
}
/**
* print_sort - prints
* @array: array
* @size: size
* @init: initialize
* 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);
}