查找一个数组中第二大的数的下标并输出

来源:互联网 发布:战地1 为什么淘宝便宜 编辑:程序博客网 时间:2024/06/01 10:21

这几天笔试中有一个题目,让输出一个数组中第二大的数的下标。第一想法就是排序,然后输出第二大的数组的下标,但是排序的话会出现交换,原数的下标也会变。所以楼主想把原数组复制一份保存下来,然后对原数组排序,找出第二大的数,与复制的数组比较,然后输出下标。这里有一个问题,如果直接写

int []a = {};

int []b = a;

当数组a中发生变化的时候,b中也会发生变化。这里涉及到了传值和传址的问题。在复制数组的时候,也叫做深复制和浅复制。经过几次错误的尝试之后,最终得到的代码如下

public class FindSecondMax {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubint[] a = { 1, 3, 8, 5, 6, 9, 2, 4 };int res = findSecondMax(a);for (int i = 0; i < a.length; i++) {System.out.print(a[i] + "  ");}System.out.println(res);}public static int findSecondMax(int[] a) {int result = -1;int[] b = a.clone();//数组的深复制//第一次输出b数组for (int i = 0; i < b.length; i++) {System.out.print(b[i]+"  ");}System.out.println();for (int i = 0; i < a.length; i++) {for (int j = 1; j < a.length; j++) {if (a[j] < a[j - 1]) {int temp = a[j];a[j] = a[j - 1];a[j - 1] = temp;}}}int x = a[a.length - 2];System.out.println("x="+x);//第二次输出b数组,和改变之前的a数组一样的for (int i = 0; i < b.length; i++) {System.out.print(b[i]+"  ");}System.out.println();for (int i = 0; i < b.length; i++) {if (x == b[i]) {result = i;}}return result;}}

输出结果

1  3  8  5  6  9  2  4  
x=8
1  3  8  5  6  9  2  4  
1  2  3  4  5  6  8  9  2
最后一个数字2,表示第二大的数的下标是2

1 0