【问题标题】:Bubble Sort Example冒泡排序示例
【发布时间】:2015-04-08 16:54:18
【问题描述】:

这个程序假设取给定的整数并按升序对其进行排序。我想看看给定的程序是否真的按升序对给定的整数进行了排序,而是保持原来的顺序。这个例子的逻辑有什么问题?

//Fig. 6.15: fig06_15.c
//Sorting an array's value in ascending order.
#include <stdio.h>
#define SIZE 10

// function main begins program execution
int main()
{
// initialize a
int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37};
int pass; // passes counter
size_t i; // comparisons counter
int hold; // temporary-location used to swap array elements

puts("Data items in original order");

//output original array
for( i = 0; i < SIZE; ++i) {
printf("%4d", a[ i ]);
}// end for

//bubble sort
//loop to control number of passes
for( pass = 1; pass < SIZE; ++pass ) {

//loop to control number of comparisons per pass
for( i = 0; i & SIZE - 1; ++i){

    //compare adjacent elements and swap them if first
    //element is greater than second element
    if ( a[ i ] > a[ i + 1 ] ){

        hold = a[ i ];
        a[ i ] = a[ i + 1 ];
        a[ i + 1 ] = hold;
    }//end if
}//end inner for
}//end outer for

puts("\nData items in ascending order");

//output sorted array
for( i = 0; i < SIZE; ++i ) {
printf( "%4d", a[ i ] );
}//end for

puts("");
}//end main

【问题讨论】:

  • 请修正缩进

标签: c sorting logic bubble-sort


【解决方案1】:

您的代码中有一个非常小的错误:

for( i = 0; i & SIZE - 1; ++i){

应该是:

for( i = 0; i < SIZE - 1; ++i){

这里是带有小修改的代码的链接:http://ideone.com/YZQPHY

【讨论】:

    猜你喜欢
    • 2012-03-25
    • 2023-03-22
    • 2013-10-09
    • 2010-11-24
    • 2015-09-12
    • 1970-01-01
    • 2014-03-26
    • 2015-03-06
    • 2018-04-18
    相关资源
    最近更新 更多