在 c++ 中将数字从列表排序到数组中的气泡排序问题
Problem with bubble sorting numbers from a list then into an array in c++
我需要编写一个程序来读取数字列表,并在排序之前和之后打印数组两次。
这是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 << ' ' ;
}
相关文章:
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 显示错误输出的简单数组排序程序
- 为什么我的排序算法会更改数组值
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 合并排序不排序自创建数组类 c++
- 带有枚举方向/类型的气泡排序结构数组
- 为什么指针在对二维数组进行排序时无法正常工作?
- 排序并行数组
- 如何在数组 c++ 中对字符串进行排序
- 为什么在此排序算法实现中,向量明显比数组慢?
- 如何对不在数组中的变量进行排序?
- C++数组与向量排序(在我的情况下,向量比数组慢~2.5倍(无优化))
- 按字母顺序对结构内数组变量中的名称进行排序
- 使用排序函数 c++ 对字符数组进行排序
- 使用 std::sort 对二维 c 数组进行排序
- 使用STL对用户输入数组进行排序的错误有什么解决方案吗?
- 使用 std::sort 对 C 样式的 2D 数组进行部分排序
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- 对 0 、1 和 2 的数组进行排序