简体   繁体   中英

Why isn't bubble sort printing out correctly with each iteration?

The algorithm that I tried does not properly sort the code and returns a 0.

I have tried outsourcing the code to a function to make it more clear, but I just can't figure it out.

#include <stdio.h>

int main(void) 
{
    int n,i,j,size,temp,counter;
    int k;
    printf("How many numbers to sort?\n");
    scanf("%d",&size);
    int array[size];
    for(i=0;i<size;i++)
    {
        printf("Enter number %d\n",i+1);
        scanf("%d",&k);
        array[i] = k;
    }

    // if statement for every element in the array, if it is not all minimum, then the for loop below needs to be activated.
    for(j=0;j<size;j++,counter = 0) //this code runs x times, bubble sort requires x test runs.
    // each time it runs, it resets counter to 0 and counts the number of mismatched elemnts in the array sorting small to large. If counter >= 1, has to run again.
    // can make j < size or j < 2...
    {  
        printf("Iteration# %d\n",j+1);
        for(i=0;i<size;i++)
        {
            if(array[i] > array[i+1])
            {
                temp = array[i];
                array[i] = array[i+1];
                array[i+1] = temp;
                counter++;
                printf("%d\n",array[i]);
            }
        }
        if (counter == 0)
        {
            break;
        }
    }

    return 0;
}

The output works until the user finishes input, then it gives me iteration from one to five, and prints 0 instead of printing the sorted array. The goal is to sort the array with bubble method one at a time and print each step, I also want the sorting to stop after the algorithm is sorted because if the counter is 0, that means the array is sorted, and the program should cease. But it goes until 5, I'm really unsure of where the error is.

You did not initially initialized the variable count.

int n,i,j,size,temp,counter;

Also the loop tries access memory beyond the array. Write

int n,i,j,size,temp,counter = 0;

//...

for(i=1;i<size;i++)
{
    if(array[i] > array[i-1])
    {
         temp = array[i];
         array[i] = array[i-1];
         array[i-1] = temp;
         counter++;
         printf("%d\n",array[i]);
    }
}

Or you could write the outer loop like

for( counter = 0, j=0;j<size;j++,counter = 0)

to initialize counter also for the first iteration.

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