reimplement compare function for quicksort
This commit is contained in:
18
quicksort.c
18
quicksort.c
@@ -2,12 +2,12 @@
|
||||
#include "include/types.h"
|
||||
#include "include/quicksort.h"
|
||||
|
||||
static int partition(lsort_array* array, int L, int R) {
|
||||
int pivot = array->items[R]->key;
|
||||
static int partition(lsort_array* array, int L, int R, int_function_pointer compare_function) {
|
||||
lsort_item* pivot = array->items[R];
|
||||
int i = L - 1;
|
||||
|
||||
for (int j = L; j < R; j++) {
|
||||
if (array->items[j]->key < pivot) {
|
||||
if (compare_function(array->items[j], pivot) < 0) {
|
||||
i = i + 1;
|
||||
lsort_array_swap(array, i, j);
|
||||
}
|
||||
@@ -17,20 +17,20 @@ static int partition(lsort_array* array, int L, int R) {
|
||||
return i + 1;
|
||||
}
|
||||
|
||||
static void _quicksort(lsort_array* array, int L, int R) {
|
||||
static void _quicksort(lsort_array* array, int L, int R, int_function_pointer compare_function) {
|
||||
if (L < R) {
|
||||
int pivotIndex = partition(array, L, R);
|
||||
_quicksort(array, L, pivotIndex - 1);
|
||||
_quicksort(array, pivotIndex + 1, 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* array) {
|
||||
int lsort_quicksort(lsort_array* array, int_function_pointer compare_function) {
|
||||
if (array->count < 1) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
_quicksort(array, 0, (int)array->count - 1);
|
||||
_quicksort(array, 0, (int)array->count - 1, compare_function);
|
||||
|
||||
return check_sorted(array);
|
||||
}
|
||||
Reference in New Issue
Block a user