读书人

怎么找到一个数组中第三大数字并输出它

发布时间: 2013-08-13 16:43:28 作者: rapoo

如何找到一个数组中第三大数字并输出它所在的位置
面试题:如何找到一个数组中第三大数字并输出它所在的位置
延伸问题:如何找到一个数组中第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);}}

读书人网 >移动开发

热点推荐