Implement QuickSort
This commit is contained in:
45
quicksort.c
Normal file
45
quicksort.c
Normal file
@@ -0,0 +1,45 @@
|
||||
#include "include/lsort.h"
|
||||
#include "include/types.h"
|
||||
#include "include/quicksort.h"
|
||||
#include <stdio.h>
|
||||
|
||||
typedef int (*int_function_pointer)(int, int);
|
||||
|
||||
static int default_compare_function(int a, int b) {
|
||||
return a - b;
|
||||
}
|
||||
|
||||
static int partition(lsort_array_i* array, int L, int R, int_function_pointer compare_function) {
|
||||
int pivot = array->items[R];
|
||||
int i = L - 1;
|
||||
|
||||
for (int j = L; j < R; j++) {
|
||||
if (compare_function(array->items[j], pivot) < 0) {
|
||||
i = i + 1;
|
||||
lsort_array_i_swap(array, i, j);
|
||||
}
|
||||
}
|
||||
|
||||
lsort_array_i_swap(array, i + 1, R);
|
||||
return i + 1;
|
||||
}
|
||||
|
||||
static void _quicksort(lsort_array_i* array, int L, int R, int_function_pointer compare_function) {
|
||||
if (L < R) {
|
||||
int pivotIndex = partition(array, L, R, compare_function);
|
||||
_quicksort(array, L, pivotIndex - 1, compare_function);
|
||||
_quicksort(array, pivotIndex + 1, R, compare_function);
|
||||
}
|
||||
}
|
||||
|
||||
int lsort_quicksort(lsort_array_i* array, int_function_pointer compare_function) {
|
||||
if (array->count < 1) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (compare_function == NULL) compare_function = default_compare_function;
|
||||
|
||||
_quicksort(array, 0, (int)array->count - 1, compare_function);
|
||||
|
||||
return check_sorted(array) ? 1 : 0;
|
||||
}
|
||||
Reference in New Issue
Block a user