【问题标题】:How to bubble sort an array with unknown length in C如何在C中对长度未知的数组进行冒泡排序
【发布时间】:2017-10-20 12:51:35
【问题描述】:

我需要帮助来编写一个代码,该代码获取一个未知大小的数组并对其进行冒泡排序,空格之间的每个单词,(只有一个空格) 例如

坏 dba = abd abd; 我编写了一个获取已知大小的字符串的代码,我尝试修改它,但我想不出任何东西。 提前致谢。! 到目前为止我的代码是:

    gets(strB);
do
{
    flag = 0;
    for
        (q = 0; 'dont know what to put here'-J ; q++) {
        if
            (strB[q] > strB[q + 1]) 
        {
            // Swap
            temp2 = strB[q];
            strB[q] = strB[q + 1];
            strB[q + 1] = temp2;
            flag = 1;
        }
    }
    j++;
} while
    (flag != 0);

puts(strB);

【问题讨论】:

  • 您是否有一些关于数组结束位置的指示符,例如它是否由NULLEOF 终止?
  • @alexdr3x 首先你应该编写循环来确定每个子字符串的开始和结束,然后对每个这样的子字符串应用冒泡排序。
  • strlen() from string.h 可能会有所帮助。顺便说一句,你不应该使用gets(),它有不可避免的缓冲区溢出风险,在 C99 中已弃用并从 C11 中删除。
  • 啊,您必须对每个单词进行排序,而不是对整个字符串进行排序。然后,strlen() 将提供较少的帮助。您应该查看字符串中的每个字符,然后搜索空格字符和字符串结尾。
  • @alexdr3x 查看我的回答。

标签: c arrays string algorithm bubble-sort


【解决方案1】:

我们初学者应该互相帮助。:)

如果我理解正确,您需要对字符串中由空格分隔的每个单词进行排序。

你应该写两个函数。第一个函数将字符串拆分为子字符串,并为每个子字符串调用冒泡排序函数。第二个函数是冒泡排序函数。

可以通过以下方式完成

#include <stdio.h>
#include <ctype.h>

void bubble_sort( char *first, char *last )
{
    for ( size_t n = last - first, sorted = n; !( n < 2 ); n = sorted )
    {
        for ( size_t i = sorted = 1; i < n; i++ )
        {
            if ( first[i] < first[i-1] )
            {
                char c = first[i];
                first[i] = first[i-1];
                first[i-1] = c;
                sorted = i;
            }
        }
    }
}

char * sort( char *s )
{
    for ( char *p = s; *p; )
    {
        while ( isspace( ( unsigned char )*p ) ) ++p;

        if ( *p )
        {
            char *q = p;
            while ( *p && !isspace( ( unsigned char )*p ) ) ++p;
            bubble_sort( q, p );
        }
    }

    return s;
}

int main(void) 
{
    char s[] = "bad dba";

    puts( s );
    puts( sort( s ) );

    return 0;
}

程序输出是

bad dba
abd abd

考虑到函数gets 是一个不安全的函数,C 标准不再支持。而是使用 C 标准函数fgets

要通过函数 fgets 删除附加的换行符,请使用以下技巧

#include <string.h>

//...

fgets( s, sizeof( s ), stdin ); 
s[ strcspn( s, "\n" ) ] = '\0';
//...

【讨论】:

  • 非常感谢来自莫斯科的@Vlad 我会马上研究你的答案!
猜你喜欢
  • 1970-01-01
  • 2013-06-10
  • 1970-01-01
  • 2015-05-09
  • 2021-09-16
  • 1970-01-01
  • 2014-05-17
  • 2016-02-09
  • 1970-01-01
相关资源
最近更新 更多