【发布时间】:2016-01-25 19:13:17
【问题描述】:
所以,我尝试先使用输入创建一个数组,然后将其从小到大排序,然后显示该数组以进行监控。
所以我想出了这个代码:
#include <iostream>
using namespace std;
void pancakeSort(int sortArray[], int sortSize);
int main()
{
// Input The Array Element Value
int pancake[10];
for(int i=0; i<10; i++)
{
cout << "Person " << i+1 << " eat pancakes = ";
cin >> pancake[i];
}
// call pancake sorting function
pancakeSort(pancake, 10);
}
void pancakeSort(int sortArray[], int sortSize)
{
int length = 10;
int temp;
int stop = 10;
// this is where the array get sorting out from smallest to biggest number
for(int counter = length-1; counter>=0; counter--)
{
for(int j=0; j<stop; j++)
{
if(sortArray[j]>sortArray[j+1])
{
temp = sortArray[j+1];
sortArray[j+1] = sortArray[j];
sortArray[j]=temp;
}
}
stop--;
}
// after that, the array get display here
for(int x=0; x<sortSize; x++)
{
cout << sortArray[x] << " ";
}
}
但输出很奇怪: enter image description here
该函数已成功将数组从小到大排序,
但是有两件奇怪的事情:
1.最大的值元素(我输入的96,排序后的第10个元素),从显示中消失。
2. 出于某种原因,我没有在数组中输入值 10 。
那么,发生了什么?
【问题讨论】:
-
看看你内部循环的 if(sortArray[j]>sortArray[j+1])!当 j = 9 时会发生什么,您的索引将超出最大索引!