关于引用 简单数组数组排序 和 最大值次最大值数组元素

 
 
 
 
//通过函数调用实现求出数组的最大值和次最大值并输出 
#include <iostream>
using namespace std;
void Max_NextMax(int A[],int n,int &max,int &nmax); //函数声明
int main(){
int max,nmax;
int  A[9]={2, 3, 1, 4, 5, 86,  8, 99, 55};//自定义一个有9个元素的数组 
Max_NextMax(   A,9, max,nmax );//函数调用 
return 0;
}
void Max_NextMax(int A[],int n,int &max,int &nmax){  //函数定义 
if(A[0]>=A[1]){
max=A[0];nmax=A[1];
}
else {
max=A[1];nmax=A[0];
}
for(int i=2;i<n;i++)
if(A[i]>=max){
nmax=max;max=A[i];
}
else if(A[i]>nmax)
nmax=A[i];
cout<<"最大值为:"<<max<<"\n次最大值为:"<<nmax<<endl;

}

运行结果:




//通过排序函数调用实现对特定数组排序 
#include <iostream> 
using namespace std;
void  Sort(int r[], int n); //函数声明 


int main()
{
 int r[9]={8,7, 6, 5, 3 ,2 ,4,0 ,12};//自定义一个含有9个元素的数组 
 Sort( r,9) ;//函数调用   注意引用格式 !! 
 for(int i=0;i<=8;i++)
{
 
cout<<r[i]<<" "<<endl;
}
 return 0;
}
void   Sort(int r[], int n)//函数定义 
 {int temp;
  for( int i=0;i<n-1;i++)
{
  int index =i;
  for(int j=i+1;j<n;j++)
  if(r[j]<r[index]) index=j;
if(index!=i) 

temp=r[i];r[i]=r[index];r[index]=temp;
}
 }
}

运行结果:




猜你喜欢

转载自blog.csdn.net/qq_35480483/article/details/78831992