【问题标题】:Why isn't bubble sort printing out correctly with each iteration?为什么每次迭代都不能正确打印出冒泡排序?
【发布时间】:2020-02-26 23:04:59
【问题描述】:

我尝试的算法没有正确排序代码并返回 0。

我曾尝试将代码外包给一个函数以使其更清晰,但我就是想不通。

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

输出一直有效,直到用户完成输入,然后它给我从一到五的迭代,并打印 0 而不是打印排序后的数组。目标是一次使用冒泡方法对数组进行排序并打印每一步,我还希望在算法排序后停止排序,因为如果计数器为 0,则表示数组已排序,程序应该停止.但是一直到5,我真的不确定错误在哪里。

【问题讨论】:

  • for(i=0;i&lt;size;i++) 然后array[i] = array[i+1];

标签: c arrays sorting bubble-sort


【解决方案1】:

您最初没有初始化变量计数。

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

循环还尝试访问数组之外​​的内存。写

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)

也为第一次迭代初始化计数器。

【讨论】:

  • 我以为我做到了? counter = 0 是外部 for 循环的一部分
  • @Junehong 最初没有初始化。
  • @Junehong 的初始代码的想法是正确的(但执行得不好):每次重新启动外部 for 循环(超过 j)时,您需要将 counter 设置为 0。最好将此初始化作为第一个语句放在 j 的 for 循环中。
  • @VladfromMoscow:在 j 的 for 循环每次开始时不重置计数器,如果在几次移动后检测到数组已经排序,则可以防止算法提前停止。
  • @JohanC 他在循环的每次迭代中初始化变量计数器,除了第一次迭代。看我的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-06
  • 2014-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多