Insertion sort sorting an ArrayList problems

arraylist, insertion-sort, java, while-loop

Solution

First problem: you're expecting `compareTo` to always return 1 for "greater than". It just returns a value greater than 0 which may be a different positive integer. So both your `== 1` comparisons should be `> 0`.

There may be other problems, but that's the first one I'd look at.

Problem

now I have been at this for a while and there is an error I am having. Now the program I am making is an address book, and I am using an insertion sort to sort an arraylist of objects which I call books(address entries). Now I soon discovered that my sorter is not sorting properly so I made a simple program to test the sorter and again it does not work. I was wondering if you guys could have a look at it and help me out. Here is my Sorter: ``` import java.util.ArrayList; public class Sorts { /** * Sorts and array of integer from low to high * pre: none * post: Integers has been sorted from low to high */ public static void insertionSort(ArrayList<String> test) { Comparable temp; int previousIndex; ArrayList<String> objectSort = test; for (int i = 1; i < objectSort.size(); i++) { temp = objectSort.get(i); previousIndex = i - 1; while ((objectSort.get(previousIndex).compareTo((String) temp)) == 1 && (previousIndex > 0)) { objectSort.set(previousIndex + 1, objectSort.get(previousIndex)); previousIndex -= 1; //decrease index to compare current item with next previous item } if (objectSort.get(previousIndex).compareTo((String) temp) == 1) { /* shift item in first element up into next element */ objectSort.set(previousIndex + 1, objectSort.get(previousIndex)); /* place current item at index 0 (first element */ objectSort.set(previousIndex, (String) temp); } else { /* place current item at index ahead of previous item */ objectSort.set(previousIndex + 1, (String) temp); } } } } ``` My simple program to test it is: ``` import java.util.ArrayList; public class Main { public static void main(String[] args){ ArrayList<String> test = new ArrayList<String>(); test.add("Roxy"); test.add("Proxy"); test.add("Moxy"); test.add("Samuel Adams"); Sorts.insertionSort(test); System.out.println(test); } } ``` To sum it up, I am having troubles with my ArrayList sorter. The problem is it wont sort correctly and I do not know why. Thank you so much in advance. If you have any questions feel free to ask. :)

Original source