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. :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With