查找次最大数

Write a function to find the second largest number in an array of integers

 

/*
File name:查找次大数.cpp
Author:杨柳
Date:2017/5/4
IDE:DEV-c++ 
*/
 #include<iostream>
 using namespace std; 
 
//先找出最大的数,放进a[o],在从a[1]到a[n-1]中找最大数为次大数 
int find(int a[],int n)   
{  
    int i; 
    int first_max=a[0];
	int second_max=0;
	for(i=1;i<n;i++)//如果数字全部一样,没有次大数 
	{
		if(a[i]==a[i-1])
		cout<<"无次最大值"<<endl; 		
	}
	
	for(i=1;i<n;i++)
	{
		if(a[i]>first_max)
			first_max=a[i];
	}
	a[0]=a[i];// 将最大数保存在a[0]中 
	second_max=a[1];
	
	for(i=2;i<n;i++)
	{
		if(a[i]>second_max)
			second_max=a[i];
	}
	return second_max;
}

int main()
{
	int a[] = {12012, 3, 45, 5, 66, 232, 65, 7, 8, 898, 56, 878, 170, 13, 5};
	int second=find(a,sizeof(a)/sizeof(a[0]));
	cout<<"这个数组中的次大数为:"<<second;
	return 0;
}

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值