-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3-quick_sort.c
More file actions
68 lines (59 loc) · 1.08 KB
/
Copy path3-quick_sort.c
File metadata and controls
68 lines (59 loc) · 1.08 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
#include "sort.h"
/**
* quick_sort - sorts an array of integers in ascending order
*
* @array: array to be sorted
*
* @size: size of the array
*/
void quick_sort(int *array, size_t size)
{
int pivot = 0;
size_t partition_index = 0;
if ((size <= 1) || array == NULL)
return;
pivot = array[size - 1];
partition_index = partition(array, size, pivot);
quick_sort(array, partition_index);
quick_sort(array + partition_index + 1, size - partition_index - 1);
}
/**
* swap - swap two integers
* @a: first integer
*
* @b: second integer
*/
void swap(int *a, int *b)
{
int tmp = 0;
tmp = *a;
*a = *b;
*b = tmp;
}
/**
* partition - partition the array to get the two
* subarrays and the index of the pivot
*
* @array: array to be sorted
* @size: size of the array
* @pivot: pivot
*
* Return: index of the pivot
*
*/
size_t partition(int *array, size_t size, int pivot)
{
int j = 0;
size_t i = 0;
for (i = 0; i < size - 1; i++)
{
if (array[i] < pivot)
{
swap(&array[i], &array[j]);
j++;
}
}
swap(&array[i], &array[j]);
print_array(array, size);
return (j);
}