Selection Sort Algorithm Using JavaScript

Selection Sort

It is a sorting algorithm in which array element is compared with all the other elements present in the array and sorted elements are moved to the left hand side of the array. This way there is a sorted part(left side) and not sorted part (right side) present in the array at any point of time. It has O(n2) time complexity making it efficient on large lists.

You can read it in detail here
 
Implementation

Following is an example of selection sort, implemented using JavaScript.
  1. function SelectionSort(input) {  
  2.     for (var i = 0; i < input.length; i++) {  
  3.         var temp = input[i];  
  4.         for (var j = i + 1; j < input.length; j++) {  
  5.             if (temp > input[j]) {  
  6.                 temp = input[j];  
  7.             }  
  8.         }  
  9.         var index = input.indexOf(temp);  
  10.         var tempVal = input[i];  
  11.         input[i] = temp;  
  12.         input[index] = tempVal;  
  13.     }  
  14. }  
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 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.
  1. var input = [8,3,2,4,7,5,0,1,6,9];  
  2. console.log(input);  
  3. SelectionSort(input);  
  4. console.log(input);  
Output of the above code,

[8, 3, 2, 4, 7, 5, 0, 1, 6, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
Please try the above code here.
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now