### What is Selection Sort:

**Selection sort** is a sorting algorithm, specifically an in-place comparison sort. It has O(*n*^{2}) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and it has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.

The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.

### Example of Selection Sort:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | Sorted sublist == ( ) Unsorted sublist == (11, 25, 12, 22,64) Least element in unsorted list == 11 Sorted sublist == (11) Unsorted sublist == (25, 12, 22, 64) Least element in unsorted list == 12 Sorted sublist == (11, 12) Unsorted sublist == (25, 22, 64) Least element in unsorted list == 22 Sorted sublist == (11, 12, 22) Unsorted sublist == (25, 64) Least element in unsorted list == 25 Sorted sublist == (11, 12, 22, 25) Unsorted sublist == (64) Least element in unsorted list == 64 Sorted sublist == (11, 12, 22, 25, 64) Unsorted sublist == ( ) |

### Program to implement Selection Sort in C++:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | /* * Program to Implement Selection Sort in C++ */ #include<stdio.h> #include<iostream> using namespace std; int main() { int lowindex,lowkey,temp,n; cout<<"enter the number of valuesn"; cin>>n; int a[n]; cout<<"enter values of arrayn"; for (int i = 0; i < n; i++) { cin>>a[i]; } for (int i = 0; i <= n - 1; i++) { lowindex = i; lowkey = a[i]; for (int j = i + 1; j <= n; j++) { if (a[j] < lowkey) { lowkey = a[j]; lowindex = j; } } temp = a[i]; a[i] = a[lowindex]; a[lowindex] = temp; } cout<<"After sortingn"; for (int k = 0; k < n; k++) { cout<<a[k]<<endl; } return 0; } |

### OUTPUT:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | enter the number of values 7 enter values of array 32 56 16 9 5 12 75 After sorting 5 9 12 16 32 56 75 |

## Leave a Reply