簡體   English   中英

為什么每次迭代都不能正確打印出冒泡排序?

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

我嘗試的算法沒有正確排序代碼並返回 0。

我曾嘗試將代碼外包給 function 以使其更清晰,但我就是想不通。

#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;
}

output 一直工作到用戶完成輸入,然后它給我從一到五的迭代,並打印 0 而不是打印排序數組。 目標是一次使用冒泡方法對數組進行排序並打印每一步,我還希望在算法排序后停止排序,因為如果計數器為 0,則表示數組已排序,程序應該停止. 但它一直持續到 5,我真的不確定錯誤在哪里。

您最初沒有初始化變量計數。

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

此外,循環嘗試訪問數組之外的 memory。

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]);
    }
}

或者你可以像這樣寫外循環

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

也為第一次迭代初始化計數器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM