Notes for lab on Insertion Sort

The assignnment is to implement Insertion Sort on an array of integers. Given an array with the numbers in any order, move the numbers around so that the numbers are in the array in decreasing order.

There are several methods to do this, the method you are to use is called Insertion Sort. Insertion Sort works by moving numbers up in the array until they are in their proper place. If the array is named a[], first a[1] is moved up, then a[2], then a[3], and so on, until all elements find their proper place in the array.

To move an element up in the array, swap the value in a[i] with the value in a[i-1] if,

     a[i] > a[i-1]
But be careful that i>0, else you will be trying to look at non-existant location -1.

Hints:
Start with SwapArray.java. Either extend the class or rename it to SortArray.java, in either case, add the needed methods.

Personally, I break down the problem into intuitively coherent yet small sub-problems and then write a method to accomplish the sub-problem. Once written and tested, I use that method in other methods, building up to the final goal.

I would first write a method putInPlace(int i) that moves the value at a[i] up according to the method described. Then I would write the insertionSort() method which orchestrates the invocations of putInPlace() to accomplish Insertion Sort.

You can also do this using nested while loops in a single method. Some programmers insist that too many methods make the program slow, since it takes time to set up a method call. I think that first the program must be correct, bug-free, and then we can work it over for speed.