**Selection sort** is techniques to sort the elements into a particular order.

## Logic for selection sort:-

- In this technique we compare first element within number with second number if it is small then we save these number otherwise not.
- Then again first element is compared with the 3rd element if it is less we swap first element and third element.
- Again we test first element with the fourth element and so on.
- This is pass 1 for sorting after this past we will get a smallest number at the top.
- In this pass 2, we compare a second element with the third element, if it is less we perform sorting else not. Then second compare with fourth and so on.
- This process continues till we get sorted list.
- The number of passes for selection sort is array
**n -1.**

Example:- Consider following array of 5 number and perform selection sort.

**Pass 4:-**

Output of example

Sorted array – 10 20 50 60 70

Passes required for sorting this array N-1 = 5-1 = 4

As we have 5 number passes are 4

Time complexity of selection sort for worst case O(n).

### Advantages of selection sort:-

- It works very simple with small number of array(with minimum data).
- selection sort don’t required any additional space while implementing.

### Disadvantages of selection sort:-

- Not as efficient while working with large set of data.
- It requires n
^{2}passes of n element.

### Program for 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 27 28 29 30 31 32 33 34 35 36 |
#include <stdio.h> int main() { int array[100], n, c, d, position, swap; printf("Enter number of elements\n"); scanf("%d", &n); //Enter range of array printf("Enter %d integers\n", n); for ( c = 0 ; c < n ; c++ ) scanf("%d", &array[c]); // Enter values in array for ( c = 0 ; c < ( n - 1 ) ; c++ ) //code for selection sort { position = c; for ( d = c + 1 ; d < n ; d++ ) { if ( array[position] > array[d] ) position = d; } if ( position != c ) { swap = array[c]; array[c] = array[position]; array[position] = swap; } } printf("Sorted list in ascending order:\n"); for ( c = 0 ; c < n ; c++ ) printf("%d\n", array[c]); return 0; } |

**Output of program:**

**Enter number of elements:**

** 5**

** Enter 5 integers**

**10 2 30 4 1**

**Sorted list in ascending order:**

**1**

**2**

**4**

**10**

**30**