【问题标题】:c++ Bubble Sort vs Radix Sortc ++冒泡排序与基数排序
【发布时间】:2015-08-25 15:02:44
【问题描述】:

我一直在为一个项目开发这个程序。一切运行良好,但我的冒泡排序有问题。我运行并显示了函数的结果,但它经常显示负数,这是不应该的。而且每隔一段时间它就不能正确排序,这意味着我的冒泡排序功能没有按顺序对它们进行排序。

#include <iostream>
#include <cstdlib>
#include <ctime>

using std::cout;
using std::cin;
using std::endl;

int const temp = 10000;

void bubbleSort ( int array [ temp ] );  
void radixSort ( int * array, int arraySize );
void display ( int btime);

int main ( )
{
    int A1;
    int array [ temp ];
    char a = '\0';

    cout << "\nWould You Like To Perform Bubble and Radix Test? (y/n): ";
    cin >> a;

    while ( a == 'y' || a == 'Y' )
    {
        srand ( ( unsigned ) time ( 0 ) );

        for ( size_t i = 0; i < temp; i++ )
        {
            A1 = ( rand ( ) % temp ) + 1 ;           
            array [ i ] = A1;            
            bubbleSort ( array );
        }
    }

    while ( a == 'n' || a == 'N' )
    {
        break;
    }

    return 0;
}

void bubbleSort ( int array [ temp ] )
{
   for ( int i = 0; i < temp; i++ )
    {
        for ( int j = 0; j < temp - 1; j++ )
        {
            if ( array [ j ] > array [ j + 1 ] )
            {
                int temp = array [ j ];
                array [ j ] = array [ j + 1 ];
                array [ j + 1 ] = temp;

                //Test: to see if its working properly.
                cout << array [ j + 1 ] << endl; //idk if this should be placed here
           }
        }
    }  
}

【问题讨论】:

  • 在 for() 循环中,将一个整数添加到未初始化的数组中,然后运行 ​​bubbleSort(array)。
  • 由于问题与基数排序无关,您可能根本不应该在问题中提及。

标签: c++ arrays sorting bubble-sort


【解决方案1】:

代码中的问题:

  1. 您的while 循环。您不会在循环中设置任何中断条件。

解决方案:使用您自己喜欢的断开条件。比如:

while ( true )
    {
        cin >> a;
        if(a == 'y' || a == 'Y') {
            //your array init and bubblesrt method calling here
        } else {
           break;
        }
    }
  1. for 循环 (!) 中使用未初始化的数组调用 bubbleSort

解决方案:

bubbleSort方法调用放在for循环之外,

for ( size_t i = 0; i < temp; i++ )
   {
      A1 = ( rand ( ) % temp ) + 1 ;           
      array [ i ] = A1;            
   }
bubbleSort ( array );

以下是bubbleSort() 方法实现的“证明”,它实际上运行良好:

#include <iostream>
#include <cstdlib>
#include <ctime>

using std::cout;
using std::cin;
using std::endl;

int const TEMP = 4;

void bubbleSort ( int array [ TEMP ] );


int main ( )
{
    int array [ TEMP ] = {3,2,-1,0}; // a simple demonstration
    bubbleSort(array);

    for (int i = 0; i < TEMP; i++) {
        cout<< array[i];
    }
    return 0;
}

void bubbleSort(int array[TEMP]) {
int temp;
for (int i = 0; i < TEMP -1; i++) {
    for (int j = 0; j < TEMP -i - 1; j++) {
        if (array[j] > array[j + 1]) {
            temp = array[j];
            array[j] = array[j + 1];
            array[j + 1] = temp;
        }
    }
}

输出是:

-1023

干杯!

【讨论】:

    猜你喜欢
    • 2013-10-09
    • 2014-03-26
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多