简体   繁体   中英

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; 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. Instead use the C standard function fgets .

To remove the appended new line character by the function fgets use the following trick

#include <string.h>

//...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM