Open In App

JavaScript Program for Selection Sort

What is Selection Sort in JavaScript?

Selection sort is a simple and efficient algorithm that works on selecting either the smallest or the largest element of the list or array and moving it to the correct position.

Working of Selection Sort

Consider the following array
arr = [ 64, 25, 12, 22, 11]

This array will be sorted in the following steps:





Example: Here is the implementation of above approach




// Function to swap values
function swap(arr,xp,yp){
    [arr[xp],arr[yp]] = [ arr[yp],arr[xp]]
}
  
// Function to implement selection
function selectionSort(arr){
  
    // To get length of array
    let n = arr.length;
      
    // Variable to store index of smallest value
    let min;
      
    // variables to iterate the array
    let i , j;
    
    for( i = 0; i < n-1;++i){
        min = i;
        for(j = i+1; j < n; j++){
            if(arr[j]<arr[min]) min = j;
        }
          
        // Swap if both index are different
        if(min!=i)
        swap(arr,min,i);
    }
}
  
// Input array
const arr = [64, 25, 12, 22, 11];
  
// Display input array
console.log( "Original array: "+ arr)
  
// Sort array using custom selection sort function
selectionSort(arr);
  
// Display output
console.log("After sorting: " +arr);

Output
Original array: 64,25,12,22,11
After sorting: 11,12,22,25,64

Selection sort is a simple algorithm which is easy to understand. It works on the idea selecting the lowest value and fix it at the right place.

The time complexity of the selection sort is O(N2) as it itterate twice (use 2 loops) and the space complexity is O(1) as there is no extra memory space is required.


Article Tags :