C++实现填充数组,并将数组按照从先到大的顺序输出。

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;
} 	
    原文作者:轻时光。。
    原文地址: https://blog.csdn.net/weixin_42265727/article/details/102856602
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞