-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3-quick_sort.c
73 lines (67 loc) · 1.75 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
#include "sort.h"
#include <stdio.h>
#include <stdlib.h>
/**
* partition - scans a partition of an array of integers for values less than
* pivot value, and swaps them with first value in partition, then swaps pivot
* value with first value in partition
* @array: array of integers to be sorted
* @low: index in array that begins partition
* @high: index in array that ends partition
* @size: amount of elements in array
* Return: new index at which to start new recursive partition
*/
int partition(int *array, int low, int high, size_t size)
{
int i, j, pivot, temp;
pivot = array[high];
i = low;
for (j = low; j < high; j++)
{
if (array[j] < pivot)
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
if (array[i] != array[j])
print_array(array, size);
i++;
}
}
temp = array[i];
array[i] = array[high];
array[high] = temp;
if (array[i] != array[high])
print_array(array, size);
return (i);
}
/**
* quicksort - recursively sorts array of integers by separating into two
* partitions, using Lomuto quick sort
* @array: array of integers to be sorted
* @low: index in array that begins partition
* @high: index in array that ends partition
* @size: amount of elements in array
*/
void quicksort(int *array, int low, int high, size_t size)
{
int p;
if (low < high)
{
p = partition(array, low, high, size);
quicksort(array, low, p - 1, size);
quicksort(array, p + 1, high, size);
}
}
/**
* quick_sort - sorts an array of integers in ascending order using a quick
* sort algorithm, with Lomuto partition scheme
* @array: array of integers to be sorted
* @size: amount of elements in array
*/
void quick_sort(int *array, size_t size)
{
if (!array || size < 2)
return;
quicksort(array, 0, (int)size - 1, size);
}