## Tuesday, 22 October 2013

### Selection Sort (concept & algorithm)

Suppose an array A with N elements is in memory. Selection sort works as follows

First find the smallest element in the list and put it in the first position. Then, find the second smallest element in the list and put it in the second position  and so on.

Pass 1: Find the location LOC  of the smallest element in the list A, A, … A[N]. Then interchange A[LOC] and A. Then: A is sorted
Pass 2: Find the location LOC  of the smallest element in the sublist A, A, … A[N]. Then interchange A[LOC] and A. Then: A,A  is sorted since A <= A.
Pass 3: Find the location LOC  of the smallest element in the sublist A, A, … A[N]. Then interchange A[LOC] and A. Then: A, A,A  is sorted, since A <= A.

Pass N-1: Find the location LOC  of the smallest element in the sublist A[N-1], A[N]. Then interchange A[LOC] and A[N-1]. Then: A, A, ….. , A[N]  is sorted, since A[N-1] <= A[N].
A is sorted after N-1 pass.

### Example : selection sort example (read algo than follow steps)

#### Complexity :

f(n) = (n-1) + (n-2) + …… + 2+ 1 = n(n-1)/2 = O(n2 )