Skip to content

Instantly share code, notes, and snippets.

@declank
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save declank/7f7d1628e31408700a60 to your computer and use it in GitHub Desktop.

Select an option

Save declank/7f7d1628e31408700a60 to your computer and use it in GitHub Desktop.
Revising insertion sort...
import java.util.Arrays;
public class InsertionSorter {
public static void main(String[] args) {
String[] argsCopy = new String[args.length];
System.arraycopy(args, 0, argsCopy, 0, args.length);
System.out.println("Original: " + Arrays.toString(args));
Arrays.sort(args, null);
sort(argsCopy);
System.out.println("Arrays.sort: " + Arrays.toString(args));
System.out.println("My insertion sort: " + Arrays.toString(argsCopy));
}
public static <T extends Comparable<? super T>>
void sort(T[] array) {
T curr;
for(int i = 0; i < array.length; i++) {
curr = array[i];
// Iterate backwards over sorted sub-list
int j = i - 1;
for( ; j >= 0; j--) {
if(array[j].compareTo(curr) <= 0) break;
array[j + 1] = array[j];
}
array[j + 1] = curr;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment