-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3-quick_sort.c
More file actions
89 lines (78 loc) · 1.42 KB
/
3-quick_sort.c
File metadata and controls
89 lines (78 loc) · 1.42 KB
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
#include "sort.h"
/**
* swap - swap items
* @a: item 1
* @b: item 2
*
* Return: void
*/
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
/**
* partition - search pivot and swap items
* @array: The array to be printed
* @lo: left position init
* @hi: right position
* @size: Number of elements in @array
*
* Return: pivot number
*/
int partition(int *array, ssize_t lo, ssize_t hi, size_t size)
{
int pivot = array[hi];
ssize_t j = lo, i;
for (i = lo; i < hi; i++)
{
if (array[i] < pivot)
{
if (j != i)
{
swap(&array[j], &array[i]);
print_array(array, size);
}
j++;
}
}
if (hi != j && array[hi] != array[j])
{
swap(&array[hi], &array[j]);
print_array(array, size);
}
return (j);
}
/**
* quicksort - quick sort function with more parameters
* @array: The array to be printed
* @lo: left position init
* @hi: right position
* @size: Number of elements in @array
*
* Return: void
*/
void quicksort(int *array, ssize_t lo, ssize_t hi, size_t size)
{
if (lo < hi)
{
int pivot = partition(array, lo, hi, size);
quicksort(array, lo, pivot - 1, size);
quicksort(array, pivot + 1, hi, size);
}
}
/**
* quick_sort - quick sort function
* @array: The array to be printed
* @size: Number of elements in @array
*
* Return: void
*/
void quick_sort(int *array, size_t size)
{
if (array == NULL || size < 2)
return;
quicksort(array, 0, size - 1, size);
}