0

I've been working on implementing a bubble sort, and I can get it to swap one time through the list, but I can't get it to run more than once, and I'm not sure how to implement it. I also know that this isn't in the helpers file, this is just for testing. My code so far is

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>

//#include "helpers.h"
//void swap(int array[]);

int main()
{
    int n = 3;
    int array[] = { 3, 2, 1};
    /*printf("Before swap: %i, %i\n", array[0], array[1]);
    swap(array);
    printf("After swap: %i, %i\n", array[0], array[1]);*/
    for (int i = 0; i < n - 1; i++) {
        if (array[i] > array[i + 1]) {
            printf("before swap %i, %i\n", array[i], array[i + 1]);
            //swap(array);
            int temp = array[i];
            array[i] = array[i + 1];
            array[i + 1] = temp;
            printf("after swap %i, %i,\n", array[i], array[i + 1]);
        }

        else {
            printf("Nothing to swap\n");
        }

        for (int j = 0; j < n; j++) {
                printf("%i\n", array[j]);
        }
    }
    return 0;
}

/* void swap(int array[]) {
    int temp = array[i];
    array[i] = array[i + 1];
    array[i + 1] = temp;
}*/
0

A loop to go through the array once when it finds once the condition is true if the exchange is performed, if the array is larger it is possible that other exchanges were relayed, but that does not guarantee the complete ordering of the array, another strategy is necessary , Let's think of pseudocode, "while there is an exchange to do, we keep going through the array", this suggests a more while loop, with some kind of condition, my way would be to use a control variable, which is zero at the beginning and positive when an exchange takes place, while the variable is positive exchanges are taking place. At the beginning of the loop we do it again zero:

int counter =0
do
{
      counter = 0;  
     // your code
    ..........
}while(counter > 0);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .