I am a bit stuck doing example of selection sort, so i am using the below logic and comparing each element of left side and moving to right side if it is higher.
I am not sure if i am missing anything with this logic.
I would appreciate if someone can guide any approach when debugging the issues like this?
Note: I am currently using 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
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 7 at com.datastructureandalgo.all.selectionSort.main(selectionSort.java:26)