# Algorithm: Selection Sort ###### tags: `Algorithm` [TOC] ## What is Selection Sort? ![](https://i.imgur.com/x95ArPX.png) The Selection sort algorithm's main idea is to find the maximum or minimum element and swap them to the correct position. >**++Example:++** >Let's say we want to order numbers from smallest to biggest. We will take the first number and find the position of the smallest number present and swap with the first one. So, the smallest number will be at the beginning of the array.[color=pink] ## How to implement Selection Sort? ```java== //Selection Sort for (int i = 0; i < arr.length - 1; i++){ int index = i; for (int j = i + 1; j < arr.length; j++){ if (arr[j] < arr[index]){ index = j;//searching for lowest index } } swap(arr, i, index); } private static void swap(int[]array, int i, int d){ if(i == d){ return; } int tmp = array[i]; array[i] = array[d]; array[d] = tmp; } ``` ## Advantages & Disadvantages >**Advantage:** >1. Avoid unecessary swapping >2. Easy to use [color=lightgreen] >**Disadvantage:** >Time taken will increase by a lot depending on amount of items [color=red]