【问题标题】:Sorting array of letters in alphabetical order按字母顺序对字母数组进行排序
【发布时间】:2020-06-16 12:35:54
【问题描述】:

这个想法是扫描一个字母数组并按字母顺序对它们进行排序

#include <stdio.h>
int main(int argc, char const *argv[]){
    char letters[1000000];
    int i = 0, num_letters = 0, temp;
    scanf("%s", letters);

    while(letters[i] != '\0'){
        num_letters++;
        i++;
    }
    i = 0;
    int count = 0;
    while(count < num_letters){
        while(i < num_letters - 1){
            if(letters[i] > letters[i+1]){
                temp = letters[i + 1];
                letters[i+1] = letters[i];
                letters[i] = temp;
            }
            i++;
        }
        count++;
    }
    printf("%s", letters);
    return 0;
}

代码不起作用,我不知道为什么 例如,字符串 'adsadf' 打印回 'adadfs' 而不是 'aaddfs'

【问题讨论】:

  • 定义“不工作”
  • 如 Paul Ogilvie 所述,您的冒泡排序内部索引未正确重置。
  • 你不应该在栈上分配这么大的数组。

标签: c arrays sorting


【解决方案1】:

你必须在内部循环开始之前重置i,所以:

i = 0;
int count = 0;
while(count < num_letters){
    while(i < num_letters - 1){

应该是

int count = 0;
while(count < num_letters){
    i = 0;
    while(i < num_letters - 1){

注意:学习使用调试器以及如何单步调试代码。你会看到 i 在外部 while 循环的第二次迭代中不是正确的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多