If you write
for(int j = 0; j < numbers.length; j++)
Then you will get ArrayIndexOutOfBoundsException for the next line,
tempVar = numbers [j + 1];
Because the numbers array is 5 in length with the last index of 4 (since the index starts at 0 ). Thus, when j = 4 the loop termination condition j < numbers.length or 4 < 5 is true , but you will get access to the exception by specifying numbers [4 + 1] index.
So try
for(int j = 0; j < numbers.length -1; j++)
or
for(int j = i; j < numbers.length -1; j++)
Now for the second piece of code, can you tell me what exactly the problem is you getting?
From wild guesses, your a.compareTo(b) < 0 does not work the way you want.
Note that compareTo returns a value less than 0 if string a lexicographically less than string b .
I am confused by what exactly you want, therefore, it creates the following code that can help you overcome your problem:
import java.util.ArrayList; public class Sort{ private static ArrayList<String> list = new ArrayList<String>(); public static ArrayList<String> sortByName(String [] input) { String temp; for (int i=0; i< input.length; i++){ for(int j= i; j< input.length-1; j++){ char first = input[i].charAt(0); char sec = input[j +1].charAt(0); if (first < sec) { temp = input[j +1]; input[j +1] = input[i]; input[i] = temp; } } list.add(input[i]); } return list; } public static void main(String[] args) { String string[] = {"Ezen", "Allen" , "Wilker", "Kruden", "Crocket"}; bubbleSortByName(string); } }
The output is a list containing:
list = [Wilker, Kruden, Ezen, Crocket, Allen]