【问题标题】:Whenever I run the insertion sort program in java, exception occurs .. but i don't know why每当我在java中运行插入排序程序时,就会发生异常..但我不知道为什么
【发布时间】:2021-05-24 02:20:15
【问题描述】:

以下是我的插入排序代码,我正面临数组索引异常。

import java.util.Scanner;

public class Insertion_Sort {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=4;
        int ar[]=new int[n];
        for(int i=0;i<n;i++)
        {
            ar[i]=sc.nextInt();
        }
        for(int i=1;i<n;i++)
        {
            int c=ar[i];
            int j=i-1;
            while(ar[j]>ar[j+1] && j>=0)
            {
                ar[j+1]=ar[j];
                j--;
            }
            ar[j+1]=c;
            
        }
        for(int i=0;i<n;i++)
        {
            System.out.println(ar[i]);
        }
        

    }

}

这是我每次运行时都会遇到的异常

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 4
    at dfsd.Insertion_Sort.main(Insertion_Sort.java:17)

【问题讨论】:

  • 错误告诉你究竟出了什么问题。如何访问数组的位置 -1?
  • 具体来说,您能想到while(ar[j]&gt;ar[j+1] &amp;&amp; j&gt;=0) 可能会导致问题的时间吗? j&gt;=0不会首先被检查。
  • 第 17 行是哪一行?请不要隐藏调试所需的信息。
  • @Swapnil 错误的原因是你必须使用while (j &gt;= 0 &amp;&amp; ar[j] &gt; ar[j+1])。这是必要的。在这里查看更多信息:stackoverflow.com/questions/8759868/…
  • @Swapnil 您还对insertion sort 使用了不正确的逻辑。在while 循环中进行必要的更改后,结果输出将是错误的。改正吧。

标签: java sorting insertion-sort


【解决方案1】:

第一件事是您应该首先检查j &gt;= 0,如果发生这种情况,请检查第二个条件ar[j] &gt; ar[i]。但还有另一个问题ar 数组在此过程中发生变化,您应该使用c 而不是ar[i],因此条件为:j &gt;= 0 &amp;&amp; ar[j] &gt; c。这是您的代码的工作版本:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = 4;
    int ar[] = new int[n];
    for (int i = 0; i < n; i++) {
        ar[i] = sc.nextInt();
    }
    for (int i = 1; i < n; i++) {
        int c = ar[i];
        int j = i - 1;
        while (j >= 0 && ar[j] > c) {
            ar[j + 1] = ar[j];
            j--;
        }
        ar[j + 1] = c;

    }
    for (int i = 0; i < n; i++) {
        System.out.println(ar[i]);
    }

}

【讨论】:

    【解决方案2】:

    J>=0 应该是第一个条件。此外,您需要检查 j

    【讨论】:

    • 您还需要检查 j 这不会发生因为jwhile 循环之外被初始化为j = i-1
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多