RUNNING TIME OF SELECTION SORT
protected static < T extends Comparable < T > > selectionSort(T a[]) {
recSelectionSort(a, a.length-1);
}
protected static < T extends Comparable < T > > recSelectionSort(T a[], int lastIndex) {
if (lastIndex > 0) {
int max = 0;
for (int i = 1; i <= lastIndex; i++) {
if (a[i].compareTo(a[max]) > 0) {
max = i;
}
}
T tmp = a[lastIndex];
a[lastIndex] = a[max];
a[max] = tmp;
recSelectionSort(a, lastIndex-1);
}
}
INTUITION
Suppose we call recSelectionSort(a,n). That call will compare
a[max] to a[1],a[2],...,a[n]. Thus, a
total of n comparisions are performed. In addition, that method will
call recSelectionSort(a,n-1). That recursive call will compare
a[max] to a[1],a[2],...,a[n-1]. So,
another n-1 comparisons occur. That recursive call will also call
recSelectionSort(a,n-2), which will require n-2 comparisons,
and so on until we call recSelectionSort(a,0), which will
perform 0 comparisons.
The total number of comparisions is thus:
n + (n-1) + (n-2) + ... + 2 + 1 + 0 = n * (n + 1) / 2.
PROOF
Theorem: recSelectionSort(a,n) requres n * (n + 1) / 2 comparisions.
By Induction on n:
Thus, for all n, recSelectionSort(a,n) requres n
* (n + 1) / 2 comparisions.
In general, we say that sorting an array of size n with
recSelectionSort requires O(n^2) time.
The running time of selectionSort on an array of size n is then also O(n^2).