Created
October 28, 2022 14:04
-
-
Save mohitsharma93/c6e73d1386a9d6d9f86b520e0fbf8d52 to your computer and use it in GitHub Desktop.
Selection Sort (JavaScript) sort array by Asc/Desc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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