#include <iostream>
#include <string>
using namespace std;
void bubbleSort(int data[], int n);
int main()
{
cout << "Enter ten unsorted integers..." << endl;
int a[10];
for (int i = 0; i < 10; ++ i)
{
cout << "[" << i << "] = ";
cin >> a[i];
}
cout << endl << "Unsorted List = ";
for (int i = 0; i < 10; ++i)
cout << a[i] << ", ";
cout << endl;
cout << "Sorting..." << endl;
cout << "Sorted List = ";
bubbleSort(a, 10);
}
void bubbleSort(int data[], int n)
{
int j = 0;
bool nextEnd = true;
while (nextEnd)
{
nextEnd = false;
++j;
for (int i = 0; i < n - j; ++i)
{
if (data[i] > data[i+1])
{
int temp = data[i];
data[i] = data[i+1];
data[i+1] = data[i];
nextEnd = true;
}
}
}
for (int i = 0; i < 10; ++i)
cout << data[i] << ", ";
}
程序非常简单。向数组输入十个值。显示未分类。将它们发送到bubbleSort函数,对它们进行排序,最后显示排序列表。我遇到的问题是我没有让输出恢复工作。我测试了最后一行代码,但这不起作用。我不认为我的排序也搞砸了。如何正确显示此排序列表?
答案 0 :(得分:3)
冒泡排序中至少有一个错误。 data[i+1]
的分配不正确。它应该是:
data[i+1] = temp;
答案 1 :(得分:2)
问题是你的“交换”。它应该是:
int temp = data[i];
data[i] = data[i+1];
data[i+1] = temp;
编辑测试并正常修正。