Skip to content

Instantly share code, notes, and snippets.

@margusmartsepp
Created July 26, 2011 20:09
Show Gist options
  • Select an option

  • Save margusmartsepp/1107877 to your computer and use it in GitHub Desktop.

Select an option

Save margusmartsepp/1107877 to your computer and use it in GitHub Desktop.
insertion sort
/**
* Method sorts a list ascendingly using insertion sort algorithm.
*
* @param <T>
* Non null class, that implements comparable interface.
* @param data
* List of T type elements, to be sorted ascendingly.
* @throws java.lang.NullPointerException
* If any element in the list is 'null'.
* @throws java.lang.UnsupportedOperationException
* If list is unmodifiable or immutable.
*/
public static <T extends Comparable<? super T>> //
void insertionSort(final List<T> data)
throws java.lang.NullPointerException,
java.lang.UnsupportedOperationException {
int i, j;
for (i = 1; i < data.size(); i++) {
T temp = data.get(i);
j = i;
while ((j > 0) && (temp.compareTo(data.get(j - 1)) < 0)) {
data.set(j, data.get(j - 1));
j--;
}
data.set(j, temp);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment