/*
Swap
Swap the data of two element
Argument
element_first
The first element
element_second
The second element
size_of_element
The size of each element
Return Value
No value will return
*/
void Swap(void *element_first, void *element_second, int size_of_element)
{
void *temp_buffer = NULL;
temp_buffer = malloc(size_of_element);
if (NULL == temp_buffer)
return ;
memmove(temp_buffer, element_second, size_of_element);
memmove(element_second, element_first, size_of_element);
memmove(element_first, temp_buffer, size_of_element);
free(temp_buffer);
}
/*
Compare
Compare two character
Argument
Fisrt
The first character
Second
The second character
Return Value
The difference value
*/
int Compare(const void *element_1, const void *element_2)
{
return *(char*)element_1 - *(char*)element_2;
}
/*
QuickSort
Use the quick sort algorithm to sort the array
Argument
array
The pointer to store the data
number_of_elements
The number of elements
size_of_element
Each element's size
ElementCompare
The user defined function to compare each element
Return Value
No value will return
*/
void QuickSort(void *array, unsigned number_of_elements, unsigned size_of_element, int (*ElementCompare)(const void *element_1, const void *element_2))
{
unsigned left = 0;
unsigned right = number_of_elements;
int i = left;
int j = right;
if (left > right)
{
return ;
}
while (i != j)
{
if (j > i)
{
Swap(array + i * size_of_element, array + size_of_element * j, size_of_element);
}
else
{
while (ElementCompare(array + j * size_of_element, array + left * size_of_element) >= 0)
{
j--;
}
while (ElementCompare(array + i * size_of_element, array + left * size_of_element) < 0)
{
i++;
}
}
}
Swap(array + i * size_of_element, array + size_of_element * left, size_of_element);
QuickSort(array + left * size_of_element, i - 1 - left, size_of_element, ElementCompare);
QuickSort(array + (i + 1) * size_of_element, right - (i + 1), size_of_element, ElementCompare);
}
这是我尝试实现的一个 qsort 函数,可是我并不知道它的问题在哪里。
可以帮忙看一下吗?(百思不得其解)
我去看了《C程序设计语言》上面的两种实现方案
第一种就是专注于 int 类型的数组
第二种尽管是 void* 通用类型,但是它使用了 二维指针数组
我希望的是复现 qsort 函数,但是现在也没想出来应该怎么解决 left 和 right 参数传递的问题。
Thanks in advance!