I had to write a program for my java class as well using comparable datatypes, it didn't really explain what a comparable datatype is exactly, but this is how I used it to do an insertion sort on an array of Strings which are objects that implement comparable interface. My understanding is that you can use the comparable datatype to point to an object which implements the comparable interface, which I used below to temporarily hold a value.
/* This class implements a method that can sort string objects in an array. using the insertion sort method. Our Main Method will call the ObjectInsertionSorter Method.
*/
public class Comparable {
public static void main(String[] Args){
/*
Create an array of strings to use as a test for the program.
*/
String[] values = {"Dylan", "Daniel", "Michael", "Amanda", "Mitsy", "Sasha", "Carlos"};
/*
Call our method and pass it the values array.
*/
objectInsertionSorter(values);
/*
Display array values.
*/
for (String element : values){
System.out.print(element + " ");
}
}
public static void objectInsertionSorter(Comparable[] array){
Comparable unsortedValue; // Temporarily holds our unsorted value
int scan; // used to scan the array;
/*
This for loop steps through our array, starting at the second value.
*/
for (int index = 1; index < array.length; index++){
unsortedValue = array[index];
scan = index;
/*
This while loop compares current value to the previous value.
If the previous value is larger, then the current value is set equal to the previous one,
and our current index "scan" is decremented.
If the previous value is smaller in comparison. Then the previous value is set equal to the unsorted value.
This will insert the unsorted value to it's correct position.
*/
while(scan > 0 && array[scan - 1].compareTo(unsortedValue) > 0){
array[scan] = array[scan - 1];
scan--;
}
// sets current value to the unsorted value
array[scan] = unsortedValue;
}
}
}