Insertion Sort

[sourcecode language=”java” collapse=”false”]
/* Method: insertionSort
* Arguments: array, lowindex, highindex, reversed
* Notes: Performs insertion sort on an array with comparable elements, between the specified indices (lowindex and highindex). Function also has the feature of sorting backwards, depending on whether or not "reversed" is true (reverse) or false (don’t reverse).
*/

public void insertionSort(Comparable[] array, int lowindex, int highindex, boolean reversed) {

int i, j;
Comparable curr;

if (!reversed) { // Don’t reverse the array
for (i = lowindex + 1; i <= highindex; i++) {
curr = array[i];
for (j = i – 1; j >= lowindex && array[j].compareTo(curr) > 0; j–)
array[j + 1] = array[j];
array[j + 1] = curr;
}
}

else { // Reverse the array
for (i = lowindex + 1; i <= highindex; i++) {
curr = array[i];
for (j = i – 1; j >= lowindex && array[j].compareTo(curr) < 0; j–)
array[j + 1] = array[j];
array[j + 1] = curr;
}
}
}
[/sourcecode]

Leave a Reply

Your email address will not be published. Required fields are marked *