Selection Sort
Implementation
Following is an example of selection sort, implemented using JavaScript.
- function SelectionSort(input) {
- for (var i = 0; i < input.length; i++) {
- var temp = input[i];
- for (var j = i + 1; j < input.length; j++) {
- if (temp > input[j]) {
- temp = input[j];
- }
- }
- var index = input.indexOf(temp);
- var tempVal = input[i];
- input[i] = temp;
- input[index] = tempVal;
- }
- }
Here I am selecting the first element from the array and comparing it with the rest of the elements. Once I find the least element in the array I am swapping that with the first element. So now the first element is the smallest element in the array.
Then I am selecting the second element in the array and I am comparing it with the rest of the elements, except the first element(as it is sorted). Once I find the least element in the rest of the array (excluding the first element), I am swapping it with the second element.
I am repeating the process until I reach the end of the array. So at any given point of time left hand side of the array(sublist) is sorted and right hand side is unsorted.
- var input = [8,3,2,4,7,5,0,1,6,9];
- console.log(input);
- SelectionSort(input);
- console.log(input);
Output of the above code,
[8, 3, 2, 4, 7, 5, 0, 1, 6, 9]
Join the conversation! Your thoughts help the community grow.