简体   繁体   中英

Bubble Sort Algorithm in C – Is this it?

I'm currently a CS50x student.

I've been toying around with the search and sorting algorithms. Trying to understand them in code. Now, on the topic of bubble sort: I created what I think is a bubble sort algorithm. But I couldn't quite fit in the idea of the swap count that needs to be set to non-zero value. My algorithm (below) does sort all numbers. Where would I fit in the swap idea though? If anyone could be so kind to explain I'd really appreciate it.


#import <stdio.h>
#import <cs50.h>

int main(void)
{

    // Creating an unsorted array

    int count = 10;

    int array[count];

    for (int z = 0; z < count; z++)
        scanf("%i", &array[z]);


    // Bubble Sort

    int buffer;

    for (int b = 0; b < count; b++)
    {

        int a = 0;

        while (a < count)
        {
            if (array[a] > array[a+1])
            {
                buffer = array[a];
                array[a] = array[a+1];
                array[a+1] = buffer;
            }
            a++;
        }

    }

    printf("Sorted: ");

    for (int b = 0; b < count; b++)
        printf("%i ", array[b]);

    printf("\n");

}


The directive is #include , not #import . The idea of counting swaps is to break the outer loop if nothing is out of sequence (because there were no swaps needed in the inner loop). This code implements that:

#include <stdio.h>

int main(void)
{
    // Creating an unsorted array
    int count = 10;
    int array[count];

    for (int z = 0; z < count; z++)
        scanf("%i", &array[z]);

    putchar('\n');
    printf("%8s:", "Unsorted");
    for (int b = 0; b < count; b++)
        printf(" %i", array[b]);
    printf("\n");

    // Bubble Sort
    for (int b = 0; b < count; b++)
    {
        int a = 0;
        int num_swaps = 0;

        while (a < count - 1)
        {
            if (array[a] > array[a+1])
            {
                int buffer = array[a];
                array[a] = array[a+1];
                array[a+1] = buffer;
                num_swaps++;
            }
            a++;
        }
        if (num_swaps == 0)
            break;
    }

    printf("%8s:", "Sorted");
    for (int b = 0; b < count; b++)
        printf(" %i", array[b]);
    printf("\n");

    return 0;
}

Sample runs (source bs97.c compiled to bs97 ; home-brew random number generator random — the options used generate 10 numbers between 10 and 99 inclusive):

$ random -n 10 10 99 | bs97

Unsorted: 68 47 85 39 52 54 31 81 19 59
  Sorted: 19 31 39 47 52 54 59 68 81 85
$ random -n 10 10 99 | bs97

Unsorted: 75 85 36 11 35 87 59 63 26 36 
  Sorted: 11 26 35 36 36 59 63 75 85 87 
$ random -n 10 10 99 | bs97

Unsorted: 90 27 64 90 76 79 52 46 98 99
  Sorted: 27 46 52 64 76 79 90 90 98 99
$ random -n 10 10 99 | bs97

Unsorted: 53 60 87 89 38 68 73 10 69 84
  Sorted: 10 38 53 60 68 69 73 84 87 89
$

Note that the code avoids trailing blanks in the output.

You could also define int num_swaps = 1; outside the sorting for loop and test it in the main loop condition:

for (int b = 0; b < count - 1 && num_swaps > 0; b++)
{
    num_swaps = 0;

and remove the if (num_swaps == 0) break; from the end of the loop. The inner loop could be a for loop too. And the first cycle of the outer loop moves the largest value to the end of the array, so you can shorten the inner cycle so it has less work to do. The printing code should be factored into a function, too.

#include <stdio.h>

static void dump_array(const char *tag, int size, int data[size])
{
    printf("%8s (%d):", tag, size);
    for (int i = 0; i < size; i++)
        printf(" %i", data[i]);
    printf("\n");
}

int main(void)
{
    // Creating an unsorted array
    int count = 10;
    int array[count];

    for (int z = 0; z < count; z++)
    {
        if (scanf("%i", &array[z]) != 1)
        {
            fprintf(stderr, "Failed to read number %d\n", z + 1);
            return 1;
        }
    }

    putchar('\n');
    dump_array("Unsorted", count, array);

    // Bubble Sort
    int num_swaps = 1;
    for (int b = 0; b < count - 1 && num_swaps > 0; b++)
    {
        num_swaps = 0;
        for (int a = 0; a < count - b - 1; a++)
        {
            if (array[a] > array[a + 1])
            {
                int buffer = array[a];
                array[a] = array[a + 1];
                array[a + 1] = buffer;
                num_swaps++;
            }
        }
    }

    dump_array("Sorted", count, array);

    return 0;
}

Sample output:

$ random -n 10 10 99 | bs97

Unsorted (10): 31 82 81 40 12 17 70 44 90 12
  Sorted (10): 12 12 17 31 40 44 70 81 82 90
$

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