简体   繁体   English

冒泡排序随机数

[英]Bubble sorting random numbers

I am trying to use bubble sort to sort a set of random numbers.我正在尝试使用冒泡排序对一组随机数进行排序。 But my code results in a messed up order.但是我的代码导致顺序混乱。 For example, instead of it sorting 9 12 15 100 150,it will sort as 12 15 100 9 150. Any help will be appreciated.例如,它不是排序 9 12 15 100 150,而是排序为 12 15 100 9 150。任何帮助将不胜感激。 Below is my code.下面是我的代码。

#include <iostream>
#include <cstdlib>
using namespace std;
void sortArray(int[], int);
void showArray(const int[], int);

int main() 
{
const int MIN_VALUE = 1;
const int MAX_VALUE = 200;
int numbers[MAX_VALUE]; 

for (int count = 0; count < MAX_VALUE; count++)
   {
    numbers[count] = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE;
    cout << numbers[count]<< endl;
    sortArray(numbers, count);
    showArray(numbers, count);
   }

} 

void sortArray(int numbers[], int size)
{
   bool swap;
   int temp;
 do
{
    swap = false;
    for (int count = 0; count < (size -1); count++)
    {

        if (numbers[count] > numbers[count + 1])
        {   
            temp = numbers[count+1];
            numbers[count+1] = numbers[count];
            numbers[count] = temp;
            swap = true;
        }
    }
 } while (swap);

}
void showArray(const int numbers[], int size)
{
 for (int count = 0; count < size; count++)
     cout <<numbers[count] << endl;
}

Thanks谢谢

The sorting code is correct.排序代码正确。

The only problem is that you're calling the sort and printing out the array in the same loop that is filling the data.唯一的问题是您正在调用排序并在填充数据的同一循环中打印出数组。

You should first fill all the data, then sort, then display the sorted result.您应该先填充所有数据,然后排序,然后显示排序结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM