import java.util.Scanner;
import java.lang.Comparable;
class InsertionSort {
private InsertionSort() {}
private static boolean less(Comparable v, Comparable w) {
return (v.compareTo(w) < 0);
}
private static void exch(Object[] a, int i, int j) {
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
}
private static void sort(Comparable[] a) {
int length = a.length;
for (int i = 0; i < length; i++) {
// Maintain Invariant
for (int j = i; j > 0; j--) {
if (less(a[j], a[j - 1])) { // Invariant broken, fix it.
exch(a, j, j - 1);
}
}
}
// Postcondition: assert isSorted(a)
}
private static void show(Object[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
private static Integer[] readAllInts() {
Scanner scanner = new Scanner(System.in);
int numberOfItems;
Integer[] items;
if (scanner.hasNext()) {
numberOfItems = scanner.nextInt();
items = new Integer[numberOfItems];
} else {
// mybe throw an error?
return new Integer[0];
}
int i = 0;
while(scanner.hasNext() && i < numberOfItems) {
items[i] = scanner.nextInt();
i++;
}
return items;
}
public static void main(String[] args) {
Integer[] items = InsertionSort.readAllInts();
InsertionSort.sort(items);
InsertionSort.show(items);
}
}
Above is the implementation of the insertion sort algorithm. I want learn how to write algorithms as well Clean Code. Now below are the points which I have taken care of or am concerned about.
- Kept meaningful names.
- Declared variables near their usage.
- Suppose, this code needs to consumed by many clients then where and what exception I should handle and throw.
- Kept variable scopes to as local as possible for easy GC.
- Most of the methods are static because I don't think they belong to a particular object.
That's it for now, I will keep updating the list if something comes to me later.
Ref: Algorithms