Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

JavaScript Searching and Sorting Algorithm: Sorts an array of numbers, using the selection sort algorithm

JavaScript Searching and Sorting Algorithm: Exercise-5 with Solution

Write a JavaScript program to sort a list of elements using the Selection sort algorithm.

The selection sort improves on the bubble sort by making only one exchange for every pass through the list.

Pictorial Presentation: Selection Sort

C sharp selection short

Sample Solution-1:

JavaScript Code:

// Selection sort with O(n^2) time complexity

function Selection_Sort(arr, compare_Function) {

  function compare(a, b) {
   return a - b;
   } 
  var min = 0;
  var index = 0;
  var temp = 0;

 //{Function} compare_Function Compare function
  compare_Function = compare_Function || compare;

  for (var i = 0; i < arr.length; i += 1) {
    index = i;
    min = arr[i];

    for (var j = i + 1; j < arr.length; j += 1) {
      if (compare_Function(min, arr[j]) > 0) {
        min = arr[j];
        index = j;
      }
    }

    temp = arr[i];
    arr[i] = min;
    arr[index] = temp;
  }

  //return sorted arr
  return arr;
}

console.log(Selection_Sort([3, 0, 2, 5, -1, 4, 1], function(a, b) { return a - b; })); 
console.log(Selection_Sort([3, 0, 2, 5, -1, 4, 1], function(a, b) { return b - a; }));

Sample Output:

[-1,0,1,2,3,4,5]
[5,4,3,2,1,0,-1]

Flowchart:

JavaScript Sharp Searching and Sorting Algorithm Exercises: Sorts an array of numbers, using the selection sort algorithm

Sample Solution-2:

  • Use the spread operator (...) to clone the original array, arr.
  • Use a for loop to iterate over elements in the array.
  • Use Array.prototype.slice() and Array.prototype.reduce() to find the index of the minimum element in the subarray to the right of the current index and perform a swap, if necessary.

JavaScript Code:

const selectionSort = arr => {
  const a = [...arr];
  for (let i = 0; i < a.length; i++) {
    const min = a
      .slice(i + 1)
      .reduce((acc, val, j) => (val < a[acc] ? j + i + 1 : acc), i);
    if (min !== i) [a[i], a[min]] = [a[min], a[i]];
  }
  return a;
};

console.log(selectionSort([5, 1, 4, 2, 3]));

Sample Output:

[1,2,3,4,5]

Flowchart:

JavaScript Sharp Searching and Sorting Algorithm Exercises: Sorts an array of numbers, using the selection sort algorithm

Live Demo:

See the Pen searching-and-sorting-algorithm-exercise-5 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to sort a list of elements using Insertion sort.
Next: Write a JavaScript program to sort a list of elements using Shell sort.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



JavaScript: Tips of the Day

How to insert an item into an array at a specific index (JavaScript)?

What you want is the splice function on the native array object.

arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert). In this example we will create an array and add an element to it into index 2:

var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";

console.log(arr.join());
arr.splice(2, 0, "Lene");
console.log(arr.join());

Ref: https://bit.ly/2BXbp04