java - 选择排序在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
解决方案
推荐阅读
- python-3.x - 如何将控制台输出转换为 txt 文件(使用 python 烧瓶服务器)
- node.js - 这个场景如何实现:调用serverA上的api自动去serverB运行请求,返回response给serverA
- java - 将 TIMESTAMP 列从 PostgreSQL 映射到 LocalDate
- java - 如何将 byte[] 转换为 Java 中字节码的文本表示?
- visual-studio-code - 当我按下 Ctrl + P 时,我可以配置 VS Code 以复制选择和搜索吗?
- google-chrome-extension - Chrome 扩展通过比较 URL 来提供反馈
- debugging - VS17 Professional 15.7.5 在 ashx 文件中悬停调试时不显示变量
- javascript - 如何处理鼠标和键盘的点击事件?
- jquery - 使用jQuery在嵌套在框架中的框架中附加div
- html - Bootstrap 4 NAVBAR 包含三个项目