【发布时间】:2017-02-17 05:25:17
【问题描述】:
我必须编写一个程序,提示用户输入要读入的整数个数。然后提示用户输入这些整数。然后它将整数存储到一个向量中,并在冒泡排序过程中按升序打印排序值。 我的程序中的问题是,并非向量中的所有值都正确排序。这是我的代码:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> numbers;
int nums;
cout << "This program reads number of integers and store them into a vector."
<< "\nThen prints the values using Bubble Sort.";
cout << "\nEnter the size of the vector to be sorted using Bubble sort: ";
cin >> nums;
for (int i = 0; i < nums; i++)
{
int number;
cout << "Enter a number: ";
cin >> number;
numbers.push_back(number);
}
for (int i = 0; i < (nums - 1); i++)
{
for (i = 1; i < nums; ++i)
{
for (int j = 0; j < (nums - j); ++j)
if (numbers[j]>numbers[j + 1]) // swapping element in if statement
{
int number = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = number;
bool swap = true;
}
}
// Displaying the sorted list
cout << "\nSorted list in ascending order using Bubble Sort:\n";
for (int a = 0; a < nums; a++) //Use for loop to print the array
{
cout << numbers[a] << " ";
}
system("pause");
return 0;
}
}
例如,我输入一个 8 个整数长向量和数字: 43 6 23 1 75 34 98 76
输出是: 1 6 23 43 75 35 98 76
所以看起来数字被正确存储到第 5 个整数的一半。
【问题讨论】:
-
j < (nums - j)由于这种奇怪的情况,您最里面的循环只查看了大约一半的元素。 -
为什么你有 2 个使用 i 作为索引的 for 循环?
-
三个嵌套的
for循环中的第二个忽略了外部循环。 -
@IgorTandetnik,非常感谢!它应该是 j
-
只是为了让你的练习更有价值和 c++ish:你可以尝试实现一个在
ForwardIterators 上运行的bubble_sort函数并使用通用比较。