算法适用于整数,但由于我将它们转换为char,因此输出为零打印:
/* sort a series of lower case letters using quicksort algorithm. */
#include <stdio.h>
#define N 10
// since c gets the ascii code when returning an int for a char variable.
char quicksort(char a[], char low, char high);
char split(char a[], char low, char high);
int a[N];
int main(void)
{
int i;
printf("Enter letters to be sorted: ");
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("%s ", a[i]);
printf("\n");
return 0;
}
char quicksort(char a[], char low, char high)
{
int middle;
if (low >= high) return;
middle = split(a, low, high);
quicksort(a, low, middle - 1);
quicksort(a, middle + 1, high);
}
char split(char a[], char low, char high)
{
char 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;
}
答案 0 :(得分:2)
三个问题:
a
被声明为int
的数组,但所有函数都处理char
数组。这意味着他们不会正确地遍历数组。将其更改为char a[N]
。%c
格式说明符scanf
。%c
格式说明符printf
。答案 1 :(得分:0)
答案 2 :(得分:0)
修改后的代码仍然无效,我似乎无法找到错误。
您的问题似乎与main()
一致,与其他人建议使用char
导向数据而不是int
相似。有一些非致命的可疑选择问题,例如对数组索引使用char
数据类型;声明quicksort()
返回char
但不返回任何内容;等等。下面是代码的返工,主要是针对样式,包含各种人的建议:
/* sort a series of letters using quicksort algorithm. */
#include <stdio.h>
#define N (10)
void quicksort(char a[], int low, int high);
int split(char a[], int low, int high);
int main(void)
{
char a[N];
printf("Enter letters to be sorted: ");
for (int i = 0; i < N; i++) {
scanf("%c", &a[i]);
}
quicksort(a, 0, N - 1);
printf("In sorted order: ");
for (int i = 0; i < N; i++) {
printf("%c ", a[i]);
}
printf("\n");
return 0;
}
void quicksort(char a[], int low, int high)
{
if (low < high) {
int middle = split(a, low, high);
quicksort(a, low, middle - 1);
quicksort(a, middle + 1, high);
}
}
int split(char a[], int low, int high)
{
char 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;
}
它不会做它应该做的一切吗?
示例强>
> ./a.out
Enter letters to be sorted: aadircslne
In sorted order: a a c d e i l n r s
>