[英]How to bubble sort an array with unknown length in C
I need help to write a code that gets an array of unknown size and bubble sort it, every word between the spaces, ( only one space) for example 我需要帮助来编写代码,以获取大小未知的数组并进行气泡排序,例如,空格之间的每个单词(例如,只有一个空格)
bad dba = abd abd; 不良dba = abd abd; I wrote a code that gets a known size of strings,and I try to modify it and I can't think of anything.
我编写了一个代码,该代码获得了已知的字符串大小,然后尝试对其进行修改,但是我什么也没想到。 Thanks in advance.!
提前致谢。! my code so far is:
到目前为止,我的代码是:
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);
We beginners should help each other.:) 我们的初学者应该互相帮助。
If I have understood correctly you need to sort each word delimited by white spaces within a string. 如果我已正确理解,则需要对字符串中由空格分隔的每个单词进行排序。
You should write two functions. 您应该编写两个函数。 The first function splits a string into substrings and call a bubble sort function for each substring.
第一个函数将字符串拆分为子字符串,并为每个子字符串调用冒泡排序函数。 The second function is a bubble sort function.
第二个功能是气泡排序功能。
It can be done the following way 可以通过以下方式完成
#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;
}
The program output is 程序输出为
bad dba
abd abd
Take into account that the function gets
is an unsafe function and is not supported any more by the C Standard. 考虑到该函数
gets
是不安全的函数,C标准不再支持该函数。 Instead use the C standard function fgets
. 而是使用C标准函数
fgets
。
To remove the appended new line character by the function fgets use the following trick 要删除fgets函数添加的换行符,请使用以下技巧
#include <string.h>
//...
fgets( s, sizeof( s ), stdin );
s[ strcspn( s, "\n" ) ] = '\0';
//...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.