Skip to content

Instantly share code, notes, and snippets.

@mohitsharma93
Created October 28, 2022 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohitsharma93/c6e73d1386a9d6d9f86b520e0fbf8d52 to your computer and use it in GitHub Desktop.
Save mohitsharma93/c6e73d1386a9d6d9f86b520e0fbf8d52 to your computer and use it in GitHub Desktop.
Selection Sort (JavaScript) sort array by Asc/Desc
const arr = [2, 12, -100, -15, -2];
/**
* Selection sort is a sorting algorithm that selects the smallest element from an unsorted list in each iteration
* and places that element at the beginning of the unsorted list.
* @param {*} arr
* @returns Array sorted.
* Uses:
* 1. checking of all the elements is compulsory.
* 2. cost of swapping does not matter.
* 3. a small list is to be sorted.
*/
function selectionSort(arr) {
for (let i = 0; i < arr.length - 1; i++) {
// store minimum index value.
let minimumIndex = i;
// To sort in descending order, change > to < in this line.
// Select the minimum element in each loop.
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minimumIndex]) minimumIndex = j
}
// swap only if both value are not same.
if (arr[minimumIndex] != arr[i]) {
console.log('swap')
// swap the position of two elements.
// put min at the correct position
let temp = arr[minimumIndex];
arr[minimumIndex] = arr[i];
arr[i] = temp;
}
}
return arr;
}
console.log(selectionSort(arr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment