冒泡排序未正确排序或输出数组值
Bubble sort is not sorting or outputting array values properly
我有一个程序,它接受最少三个分数,最多三十个分数,并将它们存储在一个数组中。我试图在一个函数中使用冒泡排序,该函数按升序对用户输入的值进行排序。排序没有按升序输出值,这是我在过去一个小时里一直试图解决的问题。我试图修复的代码部分位于"sortAcending"中
#include <iostream>
#include <iomanip>
using namespace std;
void programInfo();
void inputList(double arr[], int &count);
void printList(double arr[], int n, int &count);
void sortAscending(double arr[], int n, int &count);
int main()
{
double endProgram = 0;
const int size = 30;
double arr[size];
int count = 0;
int n = 0;
while(endProgram != -1 || endProgram != -1.0)
{
programInfo();
inputList(arr, count);
printList(arr, n, count);
sortAscending(arr, n, count);
cout << "n";
cout << "Run program again? Enter -1 or -1.0 to end program."<< endl;
cin >> endProgram;
if (endProgram == -1 || endProgram == -1.0)
{
cout << "Thank you for using my program." << endl;
}
}
}
void programInfo()
{
cout << "Statistical Calculator." << endl;
cout << "Please follow instructions carefully." << endl;
cout << "Enter one value at a time up to 30 values." << endl;
cout << "You must enter valid data or program will not work." << endl;
cout << "Enter -1 to signal end of data (-1 or -1.0)" << endl;
}
void inputList(double arr[], int &count)
{
count = 0;
char answer;
cout <<"Input at least three values minimum, thirty values maximum." << endl;
while (count < 30)
{
cout <<"Please enter a value." << endl;
cin >> arr[count];
count++;
if (count == 3)
{
cout << "You have entered the minimum amount of values necessary." << endl;
cout << "Do you want to stop inputting values? (y/n)" << endl;
cin >> answer;
if (answer == 'y')
{
break;
}
}
}
}
void printList(double arr[], int n, int &count)
{
cout <<"Here is the list of values entered:" << endl;
for (n = 0; n < count; n++)
{
cout << setw(8) << arr[n];
}
}
void sortAscending(double arr[], int n, int &count)
{
double temp;
for (n = 0; n < count; n++)
{
for (int i = 0; i < count - 1; i++)
{
if(arr[i] < arr[n])
{
temp = arr[n];
arr[n] = arr[i];
arr[i] = temp;
}
cout << arr[n] << endl;
}
}
}
嗨,你的问题是,在冒泡排序中,你不应该将n与i进行比较,也就是插入排序,你必须将i与i+1进行比较,这就是为什么循环中的条件是i<count-1.
同样,根据建议,您必须在双循环之外打印数组,并使用另一个循环。
希望能有所帮助。
for (int n = 0; n < count; n++)
{
for (int i = 0; i < count - 1; i++)
{
if(arr[i] < arr[i+1])
{
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
}
for(int i = 0; i < count; i ++){
cout<<arr[i]<<" ";
}
看起来您是在进行排序而不是排序之后输出值。我会从那里删除cout,然后遍历数组以在它们排序后打印。
相关文章:
- 使用递归输出数组
- C++ 输出数组中的最高元素
- 空指针(为缺少的输出数组调用的 create() 在 create,文件 /home/m/OpenCV/modules/
- C++ 为什么我会得到垃圾输出数组?
- C 默认如何输出数组
- 使用递归输出数组
- 从 VB6 调用的 C++ DLL 函数中的输出数组参数
- 递归函数,用于输出数组的最小数量
- 如何在 c++ 中水平输出数组
- 冒泡排序未正确排序或输出数组值
- 按相反顺序输出数组的元素
- 制作一个排列函数,输出数组中所有可能的排列
- OpenCV (c++)缝合器不写入输出数组
- 创建一个3x3x3阵列.用0到9之间的随机值填充.输出数组.找出3个最小值和3个最大值的输出
- 实现[B,C]=f(A)语法(函数f作用于具有两个或多个输出数组的数组)
- 双指针输出数组参数异常
- SWIG Python C++输出数组给出'unknown type'错误
- 以 XLL 为单位获取调用方定义的输出数组尺寸
- c++:如何从函数接收可变长度的输出数组
- 未定义的符号 输出数组 opencv fedora.