我正在执行插入排序并在我的while循环中获取一个数组超出范围的异常

时间:2016-10-06 05:49:50

标签: java algorithm sorting

插入排序

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
class solution {
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int[] a = new int[n];
        for (int i=0; i<n; i++)
        {
            a[i]=scan.nextInt();
        }
        for (int i=0; i<n; i++)
        {
            /*storing current element whose left side is checked for its
             correct position .*/
            int temp = a[i];
            int j=i;
            /* check whether the adjacent element in left side is greater or
            less than the current element. */
            while ((temp<a[j-1]) && (j>=0))
            {
                // moving the left side element to one position forward.
                a[j] = a[j-1];
                j = j-1;
                // moving current element to its  correct position.
                a[j] = temp;
            }
        }
        System.out.println("Sorted elements are:");
        for(int i=0;i<n;i++)
        {
            System.out.println(a[i]);
        }
    }
}

我不明白为什么我的代码会抛出此异常:

  

thread“main”java.lang.ArrayIndexOutOfBoundsException:-1           在solution.main(insertion.java:24)

在我的while循环中。请指导我解决这个例外。

1 个答案:

答案 0 :(得分:3)

for(int i=0;i<n;i++)

我从第一次0开始

i=0
j=i

并且第一次a[j-1]将是[(0 - 1)] = a [-1]这里

 while((temp<a[j-1]) && (j>=0)) // array index starts from 0

因此异常

所以它应该是

while((j>0) && (temp<a[j-1]) )

这是短路(&amp;&amp;)操作符的属性,只有前一个表达式为真,才会评估下一个表达式。