### The Selection sort algorithm

• Review: selection sort

• We have already seen the selection sort algorithm:

 ``` Let: the values be store in an array "a" Let: n = a.length for ( i = 0 ; i < n ; i ++ ) { Find the array element with the min. value among a[i], ..., a[n-1]; Swap this element with a[i]; } ```

• We have also seen the Selection Sort method using the interface data type:

 ``` public class SelSort { public static void sort(Comparable[] a) { int i, j, min_j; // Array indices Comparable help; // helper variable for 3-way exchange /* --------------------------------------------------- The selection sort algorithm --------------------------------------------------- */ for ( i = 0 ; i < a.length ; i ++ ) { /* --------------------------------------------------- Find array element with min. value among a[i], a[i+1], ..., a[n-1] --------------------------------------------------- */ min_j = i; // Assume elem i (a[i]) is the minimum for ( j = i+1 ; j < a.length ; j++ ) { if ( a[j].compareTo(a[min_j]) < 0 ) { min_j = j; // We found a smaller minimum, update min_j } } /* --------------------------------------------------- Swap a[i] and a[min_j] (3-way exchange) --------------------------------------------------- */ help = a[i]; a[i] = a[min_j]; a[min_j] = help; } } } ```

• Running time analysis of the Selection sort algorithm

• The work done by selection sort is given in this nested loop:

 ``` for ( i = 0 ; i < a.length ; i ++ ) { min_j = i; // Assume elem i (a[i]) is the minimum for ( j = i+1 ; j < a.length ; j++ ) { if ( a[j].compareTo(a[min_j]) < 0 ) { min_j = j; // We found a smaller minimum, update min_j } } /* --------------------------------------------------- Swap a[i] and a[min_j] (3-way exchange) --------------------------------------------------- */ help = a[i]; a[i] = a[min_j]; a[min_j] = help; } ```

• Abstract representation of the work done by selection sort:

 ``` for ( i = 0 ; i < n ; i ++ ) { for ( j = i+1 ; j < n ; j++ ) { "fundamental" operation } } ```

Running time:

 ``` i = 0: inner loop executes n-1 times i = 1: inner loop executes n-2 times i = 2: inner loop executes n-3 times ... ... i = n-2: inner loop executes 2 times i = n-1: inner loop executes 1 times ------------------------------------------------ Total = 1 + 2 + ... + (n-3) + (n-2) + (n-1) = n(n-1)/2 ```

Conclusion:

• Running time of the selection sort algorithm to sort an array of n items is:

 ``` n (n-1) --------- 2 ```