reimplement compare function for quicksort
This commit is contained in:
@@ -3,6 +3,6 @@
|
||||
|
||||
#include "types.h"
|
||||
|
||||
int lsort_quicksort(lsort_array* array);
|
||||
int lsort_quicksort(lsort_array* array, int_function_pointer compare_function);
|
||||
|
||||
#endif
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <stddef.h>
|
||||
#include "string.h"
|
||||
|
||||
|
||||
typedef struct {
|
||||
const char *buf;
|
||||
size_t len;
|
||||
@@ -13,6 +14,8 @@ typedef struct {
|
||||
int key;
|
||||
void* value;
|
||||
} lsort_item;
|
||||
typedef int (*int_function_pointer)(lsort_item*, lsort_item*);
|
||||
|
||||
|
||||
typedef struct {
|
||||
size_t count;
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -75,11 +75,15 @@ int test_radix_sort() {
|
||||
return return_code;
|
||||
}
|
||||
|
||||
int test_compare_function(lsort_item* a, lsort_item* b) {
|
||||
return a->key - b->key;
|
||||
}
|
||||
|
||||
int test_quicksort() {
|
||||
printf("lsort_quicksort()...\n");
|
||||
|
||||
lsort_array* array_quicksort = generate_samples(sample_count);
|
||||
int return_code = lsort_quicksort(array_quicksort);
|
||||
int return_code = lsort_quicksort(array_quicksort, test_compare_function);
|
||||
|
||||
lsort_array_destroy(array_quicksort, 1);
|
||||
return return_code;
|
||||
|
||||
Reference in New Issue
Block a user