0

I fixed my bubble sort code, and it correctly sorts the numbers, but it does not stop when it should. My code 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]);*/
    int swapcount = 0;
    do {
            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]);
                    int temp = array[i];
                    array[i] = array[i + 1];
                    array[i + 1] = temp;
                    printf("after swap %i, %i,\n", array[i], array[i + 1]);
                    swapcount++;
                }

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

                for (int j = 0; j < n; j++) {
                        printf("%i\n", array[j]);
                }
            }
            //return 0;
            /*int iterations = 0;
            iterations ++;
            printf("%i Iterations\n", iterations);*/
            printf("Swapcount: %i\n", swapcount);
    } while (swapcount > 0);
}

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

1 Answer 1

0
int swapcount = 0;
    do {

            swapcount = 0;

Is the correct way to not have an infinite loop. If the answers are correct, please accept them (checkbox) and in this way they will not appear unanswered, and they will appear at the top of the forum, so that others can consult

You must log in to answer this question.

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