我正在编辑一个快速排序代码,以便low,high和middle的值指向数组元素而不是整数。
这是我的代码:
#include <stdio.h>
#define N 10
void quicksort(int a[], int *low, int *high);
int split(int a[], int *low, int *high);
int main(void)
{
int a[N], i;
printf("Enter %d numbers to be sorted: ", N);
for (i=0; i<N; i++)
scanf("%d", &a[i]);
quicksort(a, &a[0], &a[N-1]);
printf("In sorted order: ");
for (i=0; i<N; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
void quicksort(int a[], int *low, int *high)
{
int *middle;
if (low >= high) return;
middle = split(a, low, high);
quicksort(a, low, middle - 1);
quicksort(a, middle + 1, high);
}
int split(int a[], int *low, int *high)
{
int part_element = *low;
for (;;) {
while (low < high && part_element <= *high)
high--;
if (low >= high) break;
*low++ = *high;
while (low < high && *low <= part_element)
low++;
if (low >= high) break;
*high-- = *low;
}
*high = part_element;
return *high;
}
我收到错误消息:
qs.c:32:12: warning: assignment makes pointer from integer without a cast [enabled by default]
middle = split(a, low, high);
^
有人可以帮我吗?仍然是编程的初学者。所有类型的帮助都表示赞赏。
答案 0 :(得分:1)
问题出在本声明中。
middle = split(a, low, high);
因为middle
是指针变量,而split
是一个返回整数值而不是指向整数的指针的函数。
您正在为指针变量middle
分配整数值。
你不被允许这样做。 :)
可能会对你有帮助。
答案 1 :(得分:0)
更改'split()'以返回'int *'而不是'int'。
从'
更改'split()'函数的最后一行return *high;
到
return high;
也许这会更好:
#include <stdio.h>
#define N 10
void quicksort(int a[], int *low, int *high);
int *split(int a[], int *low, int *high);
int main(void)
{
int a[N], i;
printf("Enter %d numbers to be sorted: ", N);
for (i=0; i<N; i++)
scanf("%d", &a[i]);
quicksort(a, &a[0], &a[N-1]);
printf("In sorted order: ");
for (i=0; i<N; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
void quicksort(int a[], int *low, int *high)
{
int *middle;
if (low >= high) return;
middle = split(a, low, high);
quicksort(a, low, middle - 1);
quicksort(a, middle + 1, high);
}
int *split(int a[], int *low, int *high)
{
int part_element = *low;
for (;;) {
while (low < high && part_element <= *high)
high--;
if (low >= high) break;
*low++ = *high;
while (low < high && *low <= part_element)
low++;
if (low >= high) break;
*high-- = *low;
}
*high = part_element;
return high;
}