# 【咨询】实现一个 qsort 函数？

``````/*
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);
}
``````

1 个赞

1 个赞

1 个赞

chatgpt回复说：

3 个赞