**An In-Depth Look At Selection Sort In C++ With Examples.**

As the name itself suggests, the selection sort technique first selects the smallest element in the array and swaps it with the first element in the array.

Next, it swaps the second smallest element in the array with the second element and so on. Thus for every pass, the smallest element in the array is selected and put in its proper position until the entire array is sorted.

**=> Check Out The Perfect C++ Training Guide Here.**

What You Will Learn:

### Introduction

Selection sort is quite a straightforward sorting technique as the technique only involves finding the smallest element in every pass and placing it in the correct position.

Selection sort works efficiently when the list to be sorted is of small size but its performance is affected badly as the list to be sorted grows in size.

Hence we can say that selection sort is not advisable for larger lists of data.

### General Algorithm

The General Algorithm for selection sort is given below:

**Selection Sort (A, N)**

**Step 1**: Repeat Steps 2 and 3 for K = 1 to N-1

** Step 2**: Call routine smallest(A, K, N,POS)

** Step 3**: Swap A[K] with A [POS]

[End of loop]

**Step 4**: EXIT

**Routine smallest (A, K, N, POS)**

**Step 1**: [initialize] set smallestElem = A[K]**Step 2**: [initialize] set POS = K**Step 3**: for J = K+1 to N -1,repeat

if smallestElem > A [J]

set smallestElem = A [J]

set POS = J

[if end]

[End of loop]**Step 4**: return POS

### Pseudocode For Selection Sort

Procedure selection_sort(array,N) array – array of items to be sorted N – size of array begin for I = 1 to N-1 begin set min = i for j = i+1 to N begin if array[j] < array[min] then min = j; end if end for //swap the minimum element with current element if minIndex != I then swap array[min[] and array[i] end if end for end procedure

An example to illustrate this selection sort algorithm is shown below.

### Illustration

**The tabular representation for this illustration is shown below:**

Unsorted list | Least element | Sorted list |
---|---|---|

{18,10,7,20,2} | 2 | {} |

{18,10,7,20} | 7 | {2} |

{18,10,20} | 10 | {2,7} |

{18,20} | 18 | {2,7,10) |

{20} | 20 | {2,7,10,18} |

{} | {2,7,10,18,20} |

From the illustration, we see that with every pass the next smallest element is put in its correct position in the sorted array. From the above illustration, we see that in order to sort an array of 5 elements, four passes were required. This means in general, to sort an array of N elements, we need N-1 passes in total.

**Given below is the implementation of selection sort algorithm in C++.**

### C++ Example

#include<iostream> using namespace std; int findSmallest (int[],int); int main () { int myarray[10] = {11,5,2,20,42,53,23,34,101,22}; int pos,temp,pass=0; cout<<"\n Input list of elements to be Sorted\n"; for(int i=0;i<10;i++) { cout<<myarray[i]<<"\t"; } for(int i=0;i<10;i++) { pos = findSmallest (myarray,i); temp = myarray[i]; myarray[i]=myarray[pos]; myarray[pos] = temp; pass++; } cout<<"\n Sorted list of elements is\n"; for(int i=0;i<10;i++) { cout<<myarray[i]<<"\t"; } cout<<"\nNumber of passes required to sort the array: "<<pass; return 0; } int findSmallest(int myarray[],int i) { int ele_small,position,j; ele_small = myarray[i]; position = i; for(j=i+1;j<10;j++) { if(myarray[j]<ele_small) { ele_small = myarray[j]; position=j; } } return position; }

**Output:**

Input list of elements to be Sorted

11 5 2 20 42 53 23 34 101 22

Sorted list of elements is

2 5 11 20 22 23 34 42 53 101

Number of passes required to sort the array: 10

As shown in the above program, we begin selection sort by comparing the first element in the array with all the other elements in the array. At the end of this comparison, the smallest element in the array is placed in the first position.

In the next pass, using the same approach, the next smallest element in the array is placed in its correct position. This continues till N elements, or till the entire array is sorted.

### Java Example

Next, we implement the selection sort technique in the Java language.

class Main { public static void main(String[] args) { int[] a = {11,5,2,20,42,53,23,34,101,22}; int pos,temp; System.out.println("\nInput list to be sorted...\n"); for(int i=0;i<10;i++) { System.out.print(a[i] + " "); } for(int i=0;i<10;i++) { pos = findSmallest(a,i); temp = a[i]; a[i]=a[pos]; a[pos] = temp; } System.out.println("\nprinting sorted elements...\n"); for(int i=0;i<10;i++) { System.out.print(a[i] + " "); } } public static int findSmallest(int a[],int i) { int smallest,position,j; smallest = a[i]; position = i; for(j=i+1;j<10;j++) { if(a[j]<smallest) { smallest = a[j]; position=j; } } return position; } }

**Output:**

Input list to be sorted…

11 5 2 20 42 53 23 34 101 22

printing sorted elements…

2 5 11 20 22 23 34 42 53 101

In the above java example as well, we apply the same logic. We repeatedly find the smallest element in the array and put it in the sorted array until the entire array is completely sorted.

Thus selection sort is the simplest algorithm to implement as we just have to repeatedly find the next smallest element in the array and swap it with the element at its appropriate position.

### Complexity Analysis Of Selection Sort

As seen in the pseudocode above for selection sort, we know that selection sort requires two for loops nested with each other to complete itself. One for loop steps through all the elements in the array and we find the minimum element index using another for loop which is nested inside the outer for loop.

Therefore, given a size N of the input array, the selection sort algorithm has the following time and complexity values.

Worst case time complexity | O( n 2 ) ; O(n) swaps |

Best case time complexity | O( n 2 ) ; O(n) swaps |

Average time complexity | O( n 2 ) ; O(n) swaps |

Space complexity | O(1) |

The time complexity of O(*n*^{2}) is mainly because of the use of two for loops. Note that the selection sort technique never takes more than O(n) swaps and is beneficial when the memory write operation proves to be costly.

### Conclusion

Selection sort is yet another simplest sorting technique that can be easily implemented. Selection sort works best when the range of the values to be sorted is known. Thus as far as sorting of data structures using selection sort is concerned, we can only sort data structure which are linear and of finite size.

This means that we can efficiently sort data structures like arrays using the selection sort.

In this tutorial, we have discussed selection sort in detail including the implementation of selection sort using C++ and Java languages. The logic behind the selection sort is to find the smallest element in the list repeatedly and place it in the proper position.

In the next tutorial, we will learn in detail about insertion sort which is said to be a more efficient technique than the other two techniques that we have discussed so far i.e. bubble sort and selection sort.

**=> Check Here To See A-Z Of C++ Training Tutorials Here.**