JavaScript

Selection Sort in JavaScript

We can create a JavaScript script to sort the elements of an array using Selection Sort. In the Selection Sort Algorithm, we find the smallest item and put it in the right place. We swap the current item for the next smallest item.
 


 
 

Script to sort array elements using selection sort
function sort(arr){
  for(var i = 0; i < arr.length; i++){
    //store the smallest index
    var min = i; 
    for(var j = i+1; j < arr.length; j++){
      if(arr[j] < arr[min]){
       // update the smallest index
       min = j; 
      }
    }
    var tmp = arr[i];
    arr[i] = arr[min];
    arr[min] = tmp;
  }
  return arr;
};

var arr = [5, 8, 11, 6, 1, 9, 3];
sort(arr);
console.log(arr);

Output:

[1, 3, 5, 6, 8, 9, 11]
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *