gpt4 book ai didi

c++ - 冒泡排序随机数

转载 作者:行者123 更新时间:2023-11-30 05:27:44 30 4
gpt4 key购买 nike

我正在尝试使用冒泡排序对一组随机数进行排序。但是我的代码导致顺序困惑。例如,它不是排序 9 12 15 100 150,而是排序为 12 15 100 9 150。任何帮助将不胜感激。下面是我的代码。

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

谢谢

最佳答案

排序代码正确。

唯一的问题是您在填充数据的同一循环中调用排序并打印出数组。

先填入所有数据,然后排序,然后显示排序后的结果。

关于c++ - 冒泡排序随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37105083/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com