获取一系列小写字母排序

时间:2016-08-02 20:43:17

标签: c arrays string quicksort

算法适用于整数,但由于我将它们转换为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;
}

3 个答案:

答案 0 :(得分:2)

三个问题:

  1. a被声明为int的数组,但所有函数都处理char数组。这意味着他们不会正确地遍历数组。将其更改为char a[N]
  2. 要阅读字符,请使用%c格式说明符scanf
  3. 要打印字符,请使用%c格式说明符printf

答案 1 :(得分:0)

scanf需要%c格式说明符。您的scanf应更改为

scanf("%c", &a[i]);

因此,您应该将a数组重新声明为char,而不是int

答案 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 
>