1
0
Fork 0

Implement quicksort based on the standard lib's implementation.

This commit is contained in:
wael 2021-09-08 15:48:44 +03:00
parent 12a805f28a
commit 885706b391
2 changed files with 71 additions and 0 deletions

View File

@ -0,0 +1,62 @@
/* This file has the implementation of the function for bubble sort. */
/* Include guards + include statements. */
#ifndef QUCIK_SORT_C
#define QUICK_SORT_C
#include <string.h>
#include "quick_sort.h"
#endif /* QUICK_SORT_C */
/* Function implementations. */
/* This is the standard (<) comparison function. */
int standard_compare_quick_sort(const void* first, const void* second) {
/* Sanity check. */
if (first == NULL && second != NULL)
return 1;
else if (first != NULL && second == NULL)
return 0;
else if (first == NULL && second == NULL)
return 0;
else
return *first <= *second;
}
/* Note that if the comparison function is NULL, then the regular comparison operator is used <. */
/* Note that if copy is set to 0, then the array is sorted in-place, otherwise a sorted copy
* is what gets returned (after allocation), leaving the original intact. */
/* Note that the comparison function should return 1 if the second argument is larger than or
* equal to the first, otherwise zero. */
/* The array's length should be passed in the length argument. */
/* Size specifies a single element's size. */
/* The function returns a NULL pointer on error, caller must check! */
void** quick_sort(const void** array, int (*comparison_function)(const void*, const void*), const size_t length, const size_t size, const int copy) {
/* Sanity check. */
if (array == NULL)
return NULL;
/* Local variables. */
void **ptr;
/* Check if to allocate a copy. */
if (copy) {
/* Allocate the array. */
ptr = (void**) malloc(length * sizeof(void*));
/* Check if the allocation failed. */
if (ptr == NULL)
return NULL;
/* Copy the arrays' contents. */
memcpy(ptr, array, length * sizeof(void*));
} else
ptr = array;
/* Rely on the standard qsort library function. */
/* Sort according to ptr, and based on the employed comparison function. */
if (comparison_function != NULL)
qsort(ptr, length, size, standard_compare_quick_sort);
else
qsort(ptr, length, size, comparison_function);
/* Return the result. */
return ptr;
}

View File

@ -0,0 +1,9 @@
/* This header defines the function for bubble sort. */
#ifndef QUICK_SORT_H
#define QUICK_SORT_H
#include <aio.h>
/* This is the standard (<) comparison function. */
int standard_compare_quick_sort(const void* first, const void* second);
/* The quicksort function's definition. */
void** quick_sort(const void** array, int (*comparison_function)(const void*, const void*), const size_t length, const size_t size, const int copy);
#endif /* QUICK_SORT_H */