Reputation: 1447
I have the following program where I try to implement an insertion sort to sort an array of strings:
import java.util.Scanner;
public class InsertionSort {
public static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("How long do you want your array to be? ");
int arraySize = console.nextInt();
String a[] = arrayOfStrings(arraySize);
System.out.println("Here is the sorted data: ");
**insert(a, arraySize);**
}
public static String[] arrayOfStrings(int size) {
String a[] = new String[size];
int i = 0;
do {
System.out.print("Input a string: ");
String input = console.next();
input = a[i];
i++;
} while(i < size);
return a;
}
public static void insert(String[] a, int size) {
**String temp = a[size];**
int j = size - 1;
while (j >= 0 && a[j].compareToIgnoreCase(temp) > 0) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = temp;
}
}
When I run the program, it crashes completely. I get an out of bounds exception on the lines marked with stars and some "NativeMethodAccessorImpl" errors. I'm pretty sure the problem is in my insertion sort but I can't figure out where and why exactly because the out of bounds error doesn't make sense to me. I'm trying to sort the strings given by the user and put them in alphabetical order from a-z.
Upvotes: 0
Views: 168
Reputation: 311
you are getting the error because size is always 1 more than the number of elements in the array. Therefore you should subract 1 from size
Here
**insert(a, arraySize - 1);**
or Here
int j = size - 1;
**String temp = a[j];**
Upvotes: 1
Reputation: 8387
Try to write your method like this:
public static void insert(String[] a) {
String temp = a[a.length-1];
int j = a.length - 1;
Upvotes: 1