在 c++ 中将数字从列表排序到数组中的气泡排序问题

Problem with bubble sorting numbers from a list then into an array in c++

本文关键字:排序 数组 气泡 问题 列表 c++ 数字      更新时间:2023-10-16

我需要编写一个程序来读取数字列表,并在排序之前和之后打印数组两次。

这是51个数字的列表 (

50 28 84 41 52 22 22 74 33 93 85 73 36 86 49 7 53 85 46 2 53 36 43 38 13 43 30 12 41 69 70 91 84 77 35 51 13 33 92 75 16 18 69 26 49 35 93 72 16 88 84)我在使用气泡排序部分的算法时遇到问题。当我单击以运行时,列表中的数字会正确显示,但排序数字的显示会给我大约 100 个随机数字。

当计算机简单地要求用户输入数字的数量和上一个分配中的数字时,我的算法已经适用于其他类型的代码,但这次我们使用列表和数组。

我觉得我的问题与我的显示语句或变量有关。

#include <iostream>
#include <fstream>
using namespace std;
// Sort numbers of the ARRAY_SIZE using Bubble Sort. 
void BubbleSort (int numbers[], int ARRAY_SIZE)
{
int i, j;
for (i = 0; i < ARRAY_SIZE; ++i)
{
for (j = 0; j < ARRAY_SIZE-i-1; ++j)
{
// Comparing consecutive data and switching values if value at j > j+1.
if (numbers[j] > numbers[j+1])
{
numbers[j] = numbers[j]+numbers[j+1];
numbers[j+1] = numbers[j]- numbers[j + 1];
numbers[j] = numbers[j]- numbers[j + 1];
}
}
// Value at n-i-1 will be maximum of all the values below this index.
}   
// Display the sorted data.
cout<<" Sorted Data ";
for (i = 0; i < ARRAY_SIZE; i++)
cout << " / " << numbers[i];
}
//**************
//*Main function
//* 
//************
int main ()
{
const int ARRAY_SIZE = 51; // constant so we can use it outside of main 
int numbers[ARRAY_SIZE];
int count = 0; // loop counter varible 
ifstream inputFile; // input file stream object 
//opening the file 
inputFile.open("file.txt");
//reading the numbers from the file then putting it into the array 
while (count < ARRAY_SIZE && inputFile >> numbers [count])
count ++;
// closing file
inputFile.close();
// Displaying the unsorted numbers 
cout << "The numbers are: " ;
for (count = 0; count < ARRAY_SIZE; count ++)
cout << numbers [count] << " ";
cout << endl;
// function for sorted numbers 
BubbleSort(numbers, ARRAY_SIZE);
return 0;
}

我得到一堆随机数,我应该按从最小值到最大值的顺序获取数字。例如2/7/等。

您的帮助总是提前感谢。

我让它工作,我知道我的显示是问题所在,我的参数适用于我的参数。 我把这段代码包含在我的主代码中,并在函数中分离了我的算法。

cout << " The sorted numbers are: " ;
for (auto num: numbers)
{
cout << num << ' ' ;
}