|
| 1 | +#include "sort.h" |
| 2 | + |
| 3 | +/** |
| 4 | + * quick_sort - Function that sorts an array based on |
| 5 | + * quick sort algorithm |
| 6 | + * @array: Array to be sorted |
| 7 | + * @size: Size of array |
| 8 | + * Return: 0 |
| 9 | + */ |
| 10 | +void quick_sort(int *array, size_t size) |
| 11 | +{ |
| 12 | + size_t pivot; |
| 13 | + |
| 14 | + if (!array || size < 2) |
| 15 | + return; |
| 16 | + |
| 17 | + print_sort(array, size, 1); |
| 18 | + |
| 19 | + /* partition and get pivot index */ |
| 20 | + pivot = partition(array, size); |
| 21 | + |
| 22 | + /* repeat for left of index */ |
| 23 | + quick_sort(array, pivot); |
| 24 | + /* repeat for index and right */ |
| 25 | + quick_sort(array + pivot, size - pivot); |
| 26 | +} |
| 27 | + |
| 28 | +/** |
| 29 | + * swap - Function that swaps two values |
| 30 | + * |
| 31 | + * @a: Fisrt value |
| 32 | + * @b: Second value |
| 33 | + * Return: 0 |
| 34 | + */ |
| 35 | +void swap(int *a, int *b) |
| 36 | +{ |
| 37 | + int tmp; |
| 38 | + |
| 39 | + tmp = *b; |
| 40 | + *b = *a; |
| 41 | + *a = tmp; |
| 42 | +} |
| 43 | + |
| 44 | +/** |
| 45 | + * partition - Function that sets the pivot for quick_sort |
| 46 | + * |
| 47 | + * @array: Array to partition |
| 48 | + * @size: Size of array |
| 49 | + * Return: (i + 1) |
| 50 | + */ |
| 51 | +size_t partition(int array[], size_t size) |
| 52 | +{ |
| 53 | + int pivot; |
| 54 | + size_t i = -1; |
| 55 | + size_t j; |
| 56 | + |
| 57 | + if (!array || size < 2) |
| 58 | + return (0); |
| 59 | + |
| 60 | + pivot = array[size - 1]; |
| 61 | + |
| 62 | + for (j = 0; j < size - 1; j++) |
| 63 | + { |
| 64 | + if (array[j] <= pivot) |
| 65 | + { |
| 66 | + i++; |
| 67 | + if (i != j) |
| 68 | + { |
| 69 | + swap(&array[i], &array[j]); |
| 70 | + print_sort(array, size, 0); |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + if (i + 1 != size - 1) |
| 75 | + { |
| 76 | + swap(&array[i + 1], &array[size - 1]); |
| 77 | + print_sort(array, size, 0); |
| 78 | + } |
| 79 | + return (i + 1); |
| 80 | +} |
| 81 | + |
| 82 | +/** |
| 83 | + * print_sort - Function that prints as it should |
| 84 | + * @array: Array to be printed |
| 85 | + * @size: Size of array |
| 86 | + * @init: Should initialize array |
| 87 | + * Return: 0 |
| 88 | + */ |
| 89 | +void print_sort(int array[], size_t size, int init) |
| 90 | +{ |
| 91 | + static int *p = (void *)0; |
| 92 | + static size_t s; |
| 93 | + |
| 94 | + if (!p && init) |
| 95 | + { |
| 96 | + p = array; |
| 97 | + s = size; |
| 98 | + } |
| 99 | + if (!init) |
| 100 | + print_array(p, s); |
| 101 | +} |
0 commit comments