教科书“修改 9.6 节的 qsort.c 程序,使 low、high 和 middle 是指向数组元素而不是整数的指针。split 函数将需要返回一个指针而不是整数”。
qsort.c 代码:
#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, 0, 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);
printf("Low");
printf("%d", low);
quicksort(a, low, middle - 1);
quicksort(a, middle + 1, high);
}
int split(int a[], int low, int high)
{
int part_element = a[low];
for (;;) {
while (low < high && part_element <= a[high])
high--;
if (low >= high) break;
a[low++] = a[high];
while (low < high && a[low] <= part_element)
low++;
if (low >= high) break;
a[high--] = a[low];
}
a[high] = part_element;
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;
int zero, nminus;
printf("Enter %d numbers to be sorted: :", N);
for (i=0; i<N; i++)
scanf("%d", &a[i]);
zero=0;
nminus=N-1;
quicksort(a, &zero, &nminus);
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;
int splitt;
if (low >= high) return;
splitt = split(a, low, high);
middle = &splitt;
quicksort(a, low, middle - 1);
quicksort(a, middle + 1, high);
}
int split(int a[], int *low, int *high)
{
int low1, high1;
low1= *low;
high1= *high;
int part_element = a[low1];
for (;;) {
while (low1 < high1 && part_element <= a[high1])
high1--;
if (low1 >= high1) break;
a[low1++] = a[high1];
while (low1 < high1 && a[low1] <= part_element)
low1++;
if (low1 >= high1) break;
a[high1--] = a[low1];
}
a[high1] = part_element;
return high1;
}
我是 c 编程的新手,不确定如何使这个程序正常工作。此尝试成功调试,但它只是吐出输入而不对其进行排序。任何帮助表示赞赏。