如何找到一个数组中第三大数字并输出它所在的位置

面试题:如何找到一个数组中第三大数字并输出它所在的位置
延伸问题:如何找到一个数组中第N大元素并输出它所在的位置
public class FindThirdLarge {
	public static void getThirdLargeNumber(int [] array,int nLarge){
		int count = 0;//大于某个数字的个数		
		int location = 0;//参考值的索引	
		int referenceValue = 0;//参考值		
		boolean flag = true;//循环执行标志		
		
		while(flag){
			referenceValue = array[location];				
			for(int i=0;i<array.length;i++){
				if( (i!=location) && (array[i]>referenceValue) ){	
					count +=1;
				}			
			}	
			if(count == (nLarge-1)){
				flag = false;
				System.out.println("第"+nLarge+"大数字是:"+referenceValue+";位置在:"+location);
			}else{
				count = 0;
				location+=1;						
				flag = true;
			}
		}
	}	
	public static void main(String[] args) {
		int ar [] = {3,6,4,9,5,2,8};		
		getThirdLargeNumber(ar,3);		
	}
}

猜你喜欢

转载自wwwjiandan.iteye.com/blog/1923209