C++实现填充数组,并将数组按照从先到大的顺序输出。
其具体实现代码如下:
#include<iostream>
using namespace std;
const int largeLength = 4;
void fillArray(int a[],int number,int& numberUsed)
{
int index=0,next;
cout<<"请输入"<<number<<"个非负数\n";
cout<<"键入负数表示结束!\n";
cout<<"请输入数字:"<<endl;
cin>>next;
while((next >= 0)&&(index < number))
{
a[index]=next;
index++;
cin>>next;
}
numberUsed = index;
cout<<"numberUsed的值为:"<<numberUsed<<endl;
}
int smallResult(int a[],int startIndex,int numberUsed)
{
int minValue = a[startIndex],
minIndex = startIndex;
for(int index = startIndex+1;index < numberUsed;index ++)
{
if(a[index] < minValue)
{
minValue = a[index];
minIndex = index;
}
}
return minIndex;
}
void swap(int& a,int& b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
}
void sort(int a[],int numberUsed)
{
int indexOfNextSmall;
int index = 0;
for(index = 0;index < numberUsed-1;index ++)
{
indexOfNextSmall = smallResult(a,index,numberUsed);
swap(a[index],a[indexOfNextSmall]);
}
}
int main()
{
int as[largeLength],numberUsed;
fillArray(as,largeLength,numberUsed);
sort(as,numberUsed);
cout<<"In sorted order the numbers are "<<endl;
for(int index = 0;index < numberUsed;index++)
cout<<as[index]<<endl;
return 0;
}