【问题标题】:Unexpected 0 appear in bubble sort function冒泡排序函数中出现意外的 0
【发布时间】:2015-04-23 09:51:12
【问题描述】:

我是 C 语言的新手,目前正在学习编写冒泡排序的基本功能。一切似乎都很好,程序的其余部分运行良好。但是,输出中出现了意外的 0。我检查了我的代码,但我不知道为什么。有人可以帮我吗? 输入输出示例:

原始号码集为:23 12 17 8 5 46 75 19 11 4 排序后的数集为:0 4 5 8 11 12 17 19 23 46

代码是:

// wirte a program of bubble sort

#include <stdio.h>
#include <string.h>

int main(void)
{
    int num[10];    // a set to store10 numbers
    int temp;   //a temporary variable
    int i,r,t,p,d;  //counters
    //store 10 numbers 
    for(i=0; i<10;++i)
    {
        printf("\nPlease enter the %dth number.\n",i+1);
        scanf("%d",&num[i]);
    }
    printf("\n");
    //display 10 numbers
    printf("The orginal number set is:");
    for(r=0; r<10; ++r)
    {
        printf("%5d",num[r]);    
    }
    printf("\n");
    //start to sort these numbers
    for (p=0;p<10;++p)    
    {
        for(t=0;t<10;++t)
        {
            if(num[t]>num[t+1])
            {
                temp=num[t];
                num[t]=num[t+1];
                num[t+1]=temp;
            } 
        } 
    }
    //print out the sorted set
    printf("The sorted number set is:");
    for(d=0;d<10;++d)
    {
        printf("%3d",num[d]);
    }
    printf("\n");
}

【问题讨论】:

  • 1.那不是冒泡排序。 2.num[t+1]在t == 9时取消引用num[10],它将作为内部循环的最后一轮,并且超出范围,因此调用未定义的行为。
  • 非常感谢。 1. 我通过将t&lt;10 更改为t&lt;9 解决了错误 2. 为什么这不是冒泡排序?冒泡排序不是把这个数和下一个数比较,然后再比较,直到得到一轮中最大的数吗?
  • 冒泡排序有交换检测。它检测排序的序列并在检测到相同时中止排序。如果任何通过未能产生交换,则根据定义,对序列进行排序并且算法完成。这就是使冒泡排序具有 O(n) 的最佳情况复杂度(具有该功能的少数排序算法之一)的原因。发送到冒泡排序的 N 个项目的排序序列将进行 (N-1) 次比较,然后终止。 see example
  • ...但不要气馁。你确实得到了算法的相邻元素比较部分正确,这是大多数人丢球的地方,所以你大部分时间都在那里。只是索引限制和交换检测关闭。祝你好运!
  • 谢谢,我会深入研究并完善功能。

标签: c bubble-sort


【解决方案1】:

当您比较值时。您还将最后一个与数组外的第一个进行比较。这恰好是 0(未定义的行为,完全依赖于编译器)并被打开。for 循环应该变成:

for (p=0;p<10;++p)    
{
    for(t=0;t<9;++t)
    {
        if(num[t]>num[t+1])
        {
            temp=num[t];
            num[t]=num[t+1];
            num[t+1]=temp;
        } 
    } 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-11
    • 2013-05-10
    • 1970-01-01
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    相关资源
    最近更新 更多