在循环的内部循环中,您正在比较和交换 pancakes[x] 和 pancakes[x + 1],而不是比较和交换 pancakes[y] 和 pancakes[y + 1]。
for (int x = 0; x < 9; x++) {
for (int y = 0; y < 9; y++) {
if (pancakes[x] > pancakes[x + 1]) {
int valueSwitched = pancakes[x];
pancakes[x] = pancakes[x + 1];
pancakes[x + 1] = valueSwitched;
}
}
}
我认为这只是一个错字。
不过我还是要指出,使用魔法并不是一个好主意
像 9 这样的数字。还有使用名称 i、j、k、l、m 和 n 作为索引的传统。
算法本身可以在数组已经排序后停止。
考虑到您可以使用标准函数std::swap 来交换数组的元素。
当数组已经排序后循环停止迭代时,我将展示这种方法
#include <iostream>
int main()
{
const size_t N = 10;
int pancakes[N];
for ( size_t i = 0; i < N; i++ )
{
std::cout << "Please input the number of pancakes person " << i + 1 << " has eaten: ";
std::cin >> pancakes[i];
}
size_t n = N;
while ( !( n < 2 ) )
{
size_t last_sorted = 0;
for ( size_t i = 1; i < n; i++)
{
if ( pancakes[i-1] > pancakes[i] )
{
int valueSwitched = pancakes[i-1];
pancakes[i-1] = pancakes[i];
pancakes[i] = valueSwitched;
last_sorted = i;
}
}
n = last_sorted;
}
std::cout << "\n-----ListSorted-----\n\n";
for ( size_t i = 0; i < N; i++ )
{
std::cout << "Person " << i + 1 << " ate: " << pancakes[i] << std::endl;
}
return 0;
}
如果以输入为例
10 1 9 2 8 3 7 4 6 5
你会得到
Please input the number of pancakes person 1 has eaten: 10
Please input the number of pancakes person 2 has eaten: 1
Please input the number of pancakes person 3 has eaten: 9
Please input the number of pancakes person 4 has eaten: 2
Please input the number of pancakes person 5 has eaten: 8
Please input the number of pancakes person 6 has eaten: 3
Please input the number of pancakes person 7 has eaten: 7
Please input the number of pancakes person 8 has eaten: 4
Please input the number of pancakes person 9 has eaten: 6
Please input the number of pancakes person 10 has eaten: 5
-----ListSorted-----
Person 1 ate: 1
Person 2 ate: 2
Person 3 ate: 3
Person 4 ate: 4
Person 5 ate: 5
Person 6 ate: 6
Person 7 ate: 7
Person 8 ate: 8
Person 9 ate: 9
Person 10 ate: 10
如果你想保持一个人和这个人吃的煎饼之间的关系,那么你应该声明一个对数组。
这是一个演示程序
#include <iostream>
#include <utility>
int main()
{
const size_t N = 10;
std::pair<size_t, int> pancakes[N];
for ( size_t i = 0; i < N; i++ )
{
std::cout << "Please input the number of pancakes person " << i + 1 << " has eaten.\n";
pancakes[i].first = i + 1;
std::cin >> pancakes[i].second;
}
size_t n = N;
while ( !( n < 2 ) )
{
size_t last_sorted = 0;
for ( size_t i = 1; i < n; i++)
{
if ( pancakes[i-1].second > pancakes[i].second )
{
auto valueSwitched = pancakes[i-1];
pancakes[i-1] = pancakes[i];
pancakes[i] = valueSwitched;
last_sorted = i;
}
}
n = last_sorted;
}
std::cout << "\n-----ListSorted-----\n\n";
for ( size_t i = 0; i < N; i++ )
{
std::cout << "Person " << pancakes[i].first << " ate: " << pancakes[i].second << std::endl;
}
return 0;
}
对于与上面相同的输入,其排序后的输出将如下所示
-----ListSorted-----
Person 2 ate: 1
Person 4 ate: 2
Person 6 ate: 3
Person 8 ate: 4
Person 10 ate: 5
Person 9 ate: 6
Person 7 ate: 7
Person 5 ate: 8
Person 3 ate: 9
Person 1 ate: 10