-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3-quick_sort.c
76 lines (70 loc) · 1.19 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
#include "sort.h"
/**
* swap - swap two numbers
* @a: first number
* @b: second number
**/
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
/**
* partition - split array around pivot
* @arr: array
* @first: first element
* @last: last element
* @size: size
* Return: i
*/
int partition(int *arr, int first, int last, size_t size)
{
int pivot = arr[last];
int i = first;
int j;
for (j = first; j < last; j++)
{
if (arr[j] <= pivot)
{
swap(&arr[i], &arr[j]);
if (i != j)
print_array(arr, size);
i++;
}
}
swap(&arr[i], &arr[last]);
if (i != j)
print_array(arr, size);
return (i);
}
/**
* quickSort - sort a part of the list
* @arr: array
* @first: first element
* @last: last element
* @size: size
* Return: nothing
*/
void quickSort(int *arr, int first, int last, size_t size)
{
int pivot;
if (first < last)
{
pivot = partition(arr, first, last, size);
quickSort(arr, first, pivot - 1, size);
quickSort(arr, pivot + 1, last, size);
}
}
/**
* quick_sort - quick sort method array
* @array: array
* @size: size
* Return: nothing
*/
void quick_sort(int *array, size_t size)
{
if (size < 2)
return;
quickSort(array, 0, size - 1, size);
}