Selection Sort

[sourcecode language=”java” collapse=”false”]
/* Method: selectionSort
* Arguments: array, lowindex, highindex, reversed
* Notes: Performs selection 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 selectionSort(Comparable[] array, int lowindex, int highindex, boolean reversed) {

int i, j;
Comparable min;
int swapindex;

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

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

Leave a Reply

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