-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3-quick_sort.c
More file actions
78 lines (69 loc) · 1.65 KB
/
Copy path3-quick_sort.c
File metadata and controls
78 lines (69 loc) · 1.65 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
#include "sort.h"
/**
* partition - this sorts the array and puts the pivot in the right position
* @array: this is the array that is to be sorted
* @start: this is the beginning of the part of the array to be partitioned
* @end: ths is the end of the part of the array to be partitioned
* @size: this is the size of the array
* Return: returns the pivot
*/
int partition(int *array, int start, int end, size_t size)
{
int i, j, buffer, pivot;
pivot = array[end];
j = start - 1;
for (i = start; i <= end - 1; i++)
{
if (array[i] < pivot)
{
j = j + 1;
if (j != i)
{
buffer = array[i];
array[i] = array[j];
array[j] = buffer;
print_array(array, size);
}
}
}
if (j + 1 != end)
{
buffer = array[end];
array[end] = array[j + 1];
array[j + 1] = buffer;
print_array(array, size);
}
return (j + 1);
}
/**
* quick - this is the quick sort algorithm
* @array: this is the array that is to be sorted
* @start: this is the point at which the sorting should start
* @end: this is the point where the sorting should end
* @size: this is the size of the array
*/
void quick(int *array, int start, int end, size_t size)
{
int p;
if (start > end)
{
return;
}
p = partition(array, start, end, size);
quick(array, start, p - 1, size);
quick(array, p + 1, end, size);
}
/**
* quick_sort - sorts an array of integers in
* ascending order using the Quick sort algorithm
* @array: this is the array that is to be sorted
* @size: this is the size of the array to be sorted
*/
void quick_sort(int *array, size_t size)
{
if (array == NULL || size < 2)
{
return;
}
quick(array, 0, size - 1, size);
}