首页 > 解决方案 > 选择排序在Java中出现错误异常

问题描述

我在做选择排序的例子时有点卡住了,所以我使用下面的逻辑并比较左侧的每个元素,如果它更高,则移动到右侧。

我不确定我是否遗漏了这个逻辑。

如果有人在调试此类问题时可以指导任何方法,我将不胜感激?

注意:我目前正在使用 Eclipse

/** * */ package com.datastructureandalgo.all;

/**
 * @author Umair
 * 
 */
public class selectionSort {

    /**
     * @param args
     */
    public static void main(String[] args) {

        int[] arrayInt = { 20, 35, -15, 7, 55, 1, -22 };

        for (int lastUnsortedIndex = arrayInt.length - 1; lastUnsortedIndex > 0; lastUnsortedIndex--) {

          

            int tempHighIndex = 0;
            for (int i = 0; i <= lastUnsortedIndex; i++) {               // line 26

                if (arrayInt[tempHighIndex] > arrayInt[i + 1]) {
                    tempHighIndex = i;
                 } else {
                    tempHighIndex = i + 1;
             }

            replace(arrayInt, tempHighIndex, lastUnsortedIndex);

        }
        
        for(int i=0;i<arrayInt.length;i++) {
            
            System.out.println(arrayInt[i]);
            
        }
        // TODO Auto-generated method stub

    }

    /**
     * @param arrayInt
     * @param tempHighIndex
     * @param lastUnsortedArray
     */
    private static void replace(int[] arrayInt, int tempHighIndex, int lastUnsortedArray) {
        // TODO Auto-generated method stub

        arrayInt[lastUnsortedArray] = arrayInt[tempHighIndex];
    }

}

-Error in Console

线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:com.datastructureandalgo.all.selectionSort.main(selectionSort.java:26) 处的索引 7 超出长度 7

标签: javaeclipsealgorithmselection-sort

解决方案


推荐阅读