Selection Sort
Selection Sort
Algorithms
12-Nov-19
Agenda
1
What is Brute Force? (Recap)
An algorithm design technique
It is a straightforward approach to solve a
12-Nov-19
problem in a very easy, yet (usually)
inefficient way.
12-Nov-19
Muzaffar Iqbal Farooqi
3
Selection Sort
• Selection sort is a simple sorting algorithm.
• This sorting algorithm is an in-place comparison-based
12-Nov-19
algorithm in which the list is divided into two parts…
• the sorted part at the left end and
12-Nov-19
• For the first position in the sorted list, the whole list is
12-Nov-19
Muzaffar Iqbal Farooqi
• We find that 14 is the second lowest value in the list and it
should appear at the second place. We swap these values.
6
How Selection Sort Works?
• The same process is applied to the next items in the array as
shown below...
12-Nov-19
Muzaffar Iqbal Farooqi
7
How Selection Sort Works?
• The same process is applied to the next items in the array as
shown below...
12-Nov-19
Muzaffar Iqbal Farooqi
8
How Selection Sort Works?
• The same process is applied to the next items in the array as
shown below...
12-Nov-19
Muzaffar Iqbal Farooqi
9
Algorithm
Step 1 − Set MIN to loca on 0
Step 2 − Search the minimum element in the list
12-Nov-19
Step 3 − Swap with value at loca on MIN
Step 4 − Increment MIN to point to next element
10
Algorithm (Revised)
• Find the smallest element. Swap it with the first element.
• Find the second-smallest element. Swap it with the second
12-Nov-19
element.
• Find the third-smallest element. Swap it with the third
11
Pseudocode
SELECTION-SORT(array,SIZE)
1. for i ← 0 to SIZE-1
2. smallest ← i
12-Nov-19
3. for j ← i + 1 to SIZE
4. if A[ j ] < A[ smallest ]
5. smallest ← j
12
Program