Selection Sort Algorithm

The selection sort algorithm is a sorting algorithm that selects the smallest element from an array of unsorted elements called a pass. In each pass, it selects an unsorted element from the array and compares it with the rest of the unsorted array.

If any element smaller than the current smallest is found, replace it with a new element. This process is repeated until there are no more small elements. The entire array is sorted in this way.

The steps performed in each pass is as follows.

  1. Given an array, A[1…n].
  2. Find the smallest element in the array, A[1…n].
  3. Replace with A[1] with the resultant smallest element and repeat the process again for a[2], and so on.
  4. Stop the search process when n-1 smallest elements are found, the last one is the largest in the array.

Selection-Sort Algorithm

Algorithm Selection-Sort(A)

for i = 1 to n-1
    i:= min

for j:= i +1 to n
    if A[j] < A[min]) then
        T: = A[min]
        A[min] := A[j]
        A[j] := T

Example of Selection Sort

In this example, we will sort 5 unsorted numbers.

Array : (44, 7, 10, 77, 33)

Pass 1: (7, 44, 10, 77, 33)

Pass 2: (7, 10, 44, 77, 33)

Pass 3: (7, 10, 33, 77, 44)

Pass 4: (7, 10, 33, 44, 77)

The sorted array is (7, 10, 33, 44, 77).

Analysis of Selection Sort

The selection-sort algorithm has 2 loops each time,  the outer loop runs n-1 time and the inner loop runs as follows.

for 1st element of outer loop = n-1 times 

for 2ndelement of outer loop = n-2 times, so on

for n-1th element or outer loop = 1 time

= ((n)(n-1))/2

= (5(5 - 1))/2

= 20/2

= 10 

Let T(n) be the total running time of selection sort then,

T(n) = (4 + 3 + 2 + 1) 

= 10 operations

The running time of the selection sort algorithm is then θ(n2) for both best-case and worst-case. Even in best-case, we will run a comparison in sub-array in the same manner as worst-case. Thus, the running time is θ(n2)

Please support us by disabling your adblocker or whitelist this site from your adblocker. Thanks!

turn of adblocker imag