Selection Sort
Selection sort is a sorting algorithm used to arrange the list of elements in ascending or descending order.
The algorithm divides the list logically into two parts : Sorted and unsorted
Sorting the list in ascending order the algorithm involves by searching for the smallest element in the list and then swapping it with the element at the first position. This swap ensures placing of first element at itssorted position.
Again the sublist from second position is searched for the second smallest element and this second smallest element is swapped with the element at the seond position. this continues till we reache the second last element of the list.
Selection sort is a sorting algorithm used to arrange the list of elements in ascending or descending order.
The algorithm divides the list logically into two parts : Sorted and unsorted
Sorting the list in ascending order the algorithm involves by searching for the smallest element in the list and then swapping it with the element at the first position. This swap ensures placing of first element at itssorted position.
Again the sublist from second position is searched for the second smallest element and this second smallest element is swapped with the element at the seond position. this continues till we reache the second last element of the list.
As per this type of sorting algorithm the smallest element is
searched and then placed at the first position. After this next smallest
element is searched in the list and then exchanged with the element at the
second position and so on.
Let us consider an array with following values:
23, 12,
34, 5, 6,
20
Smallest element is selected
23
|
12
|
34
|
5
|
6
|
20
|
and is exchanged with the element at first position.
5
|
12
|
34
|
23
|
6
|
20
|
Again second smallest
element is selected
5
|
12
|
34
|
23
|
6
|
20
|
and is exchanged with element at second position
5
|
6
|
34
|
23
|
12
|
20
|
Next element at third smallest element is selected
5
|
6
|
34
|
23
|
12
|
20
|
And isreplaced with
third smallest element
5
|
6
|
12
|
23
|
34
|
20
|
Next fourth smallest element is selected
5
|
6
|
12
|
23
|
34
|
20
|
This fourth smallest element is replaces the
element at fourth position
5
|
6
|
12
|
20
|
34
|
23
|
At last the fifth element is
selected
5
|
6
|
12
|
20
|
34
|
23
|
And is replaced with element at
fifth position
5
|
6
|
12
|
20
|
23
|
34
|
After five passes this array of six elements
is sorted
An array of N elements is sorted
with N-1 passes and the last unsorted element is automatically in sorted order.
Algorithm of Selection Sort
1. Declare a
variable MIN to store minimum value.
2. Declare
variable POS to store the p
3. Declare a
temporary variable TEMP.
4. Declare
counter variables S and P .
5. Set S=0
6. MIN=AR[S]
7. Set P=S+1
8. If
AR[P]<MIN
SET MIN=AR[P]
9. P=P+1
10. IF
(P<N-1) GOTO STEP 8
11. IF
MIN=AR[S] GOTO STEP
12. TEMP=AR[S]
13. AR[S]=MIN
14. AR[POS]=TEMP
15. S=S+1
16. IF S<N
GOTO STEP 6
17. STOP