日期:2014-05-20  浏览次数:20786 次

数组的传递问题
public class Times 
{
static int[] array = {5,2,4,1,10,9,6,3,7,8};
public static void main(String[] args)
{
long start_time = 0;long end_time = 0;
start_time = System.currentTimeMillis();
sort_mean1(array);
end_time = System.currentTimeMillis();
System.out.println("The time is:"+(start_time-end_time)+"ms");
}

static void sort_mean1(int[] a)
{
int[] b = a;
int j = 0;
int key = 0;
for(int i = 1;i<=b.length;i++)
{
key = b[i];
j = i-1;
while(j>0 && b[j]>key)
{
b[j+1] = b[j];
j = j-1;
}
b[j+1] = key;
}
System.out.println(b[10]);
}
}


上面代码为什么运行是出行java.lang.ArrayIndexOutOfBoundsException
------解决方案--------------------
public class Times {
static int[] array = { 5, 2, 4, 1, 10, 9, 6, 3, 7, 8 };

public static void main(String[] args) {
long start_time = 0;
long end_time = 0;
start_time = System.currentTimeMillis();
sort_mean1(array);
end_time = System.currentTimeMillis();
System.out.println("The time is:" + (start_time - end_time) + "ms");
}

static void sort_mean1(int[] a) {
int[] b = a;
int j = 0;
int key = 0;
for (int i = 1; i <= b.length; i++) {
key = b[i]; //主要错在这块,i不可以大于等于b数组的长度
j = i - 1;
while (j > 0 && b[j] > key) {
b[j + 1] = b[j];
j = j - 1;
}
b[j + 1] = key; //这里
}
System.out.println(b[10]); //还有这里,不能大于9
}
}