#include stdioh#include stinghvoid Q_sortint arrint begin int end ifbeginned return ; int left = begin; int right = end; int key = begin; whilebegin end whilearr end = arr key && begin end
代码中有以下错误:
-
头文件名称错误,应该是
string.h而不是sting.h。 -
if(begin>ned)中的ned应该是end。 -
在交换数组元素时,应该交换的是元素的值,而不是地址。因此,
swap(&arr[begin],&arr[end])应该改为swap(arr[begin], arr[end])。 -
调用
swap(arr [key], &arr [end])时,第一个参数应该是arr[key]而不是arr [key]。 -
在递归调用
Q_sort函数时,第一个参数应该是数组名,而不是指针。
修正后的代码如下:
#include <stdio.h>
#include <string.h>
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
void Q_sort(int arr[], int begin, int end)
{
if (begin > end)
{
return;
}
int left = begin;
int right = end;
int key = begin;
while (begin < end)
{
while (arr[end] >= arr[key] && begin < end)
{
--end;
}
while (arr[begin] <= arr[key] && begin < end)
{
++begin;
}
swap(&arr[begin], &arr[end]);
}
swap(&arr[key], &arr[end]);
key = end;
Q_sort(arr, left, key-1);
Q_sort(arr, key+1, right);
}
int main()
{
int arr[] = {6, 2, 8, 1, 9, 4, 3, 7, 5};
int n = sizeof(arr) / sizeof(arr[0]);
Q_sort(arr, 0, n-1);
for (int i = 0; i < n; ++i)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/exxt 著作权归作者所有。请勿转载和采集!