Created
May 23, 2022 20:43
-
-
Save jayantasamaddar/099b6f5aa2be84462fdccec0819fdc71 to your computer and use it in GitHub Desktop.
Implement a Selection Sort Algorithm
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
/* Method 1 - Using C Style for-loop */ | |
const selectionSort = array => { | |
const arr = array.slice(); | |
for (let i = 0; i < arr.length - 1; i++) { | |
for (let j = i; j < arr.length - 1; j++) { | |
const select = Math.min(...arr.slice(j, arr.length)); | |
if (select < arr[j]) swap(arr, j, arr.lastIndexOf(select)); | |
} | |
} | |
return arr; | |
}; |
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
/* Method 2 - Using for-in loop */ | |
const selectionSort2 = array => { | |
const arr = array.slice(); | |
for (let c in arr) { | |
for (let i = c; i < arr.length - 1; i++) { | |
const select = Math.min(arr[i], ...arr.slice(i + 1, array.length)); | |
if (select < arr[i]) swap(arr, i, arr.lastIndexOf(select)); | |
} | |
} | |
return arr; | |
}; |
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
/* Method 3 - Using while loop */ | |
const selectionSort3 = array => { | |
const arr = array.slice(); | |
let i = 0; | |
while (i < arr.length - 1) { | |
let j = i; | |
while (j < arr.length - 1) { | |
const select = Math.min(arr[i], ...arr.slice(i + 1, array.length)); | |
if (select < arr[i]) swap(arr, i, arr.lastIndexOf(select)); | |
j++; | |
} | |
i++; | |
} | |
return arr; | |
}; |
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
/* Method 4 - Using Recursive Function */ | |
const selectionSort4 = array => { | |
const recursiveSort = (arr, indx) => { | |
let i = indx; | |
if (i === arr.length - 1) return arr; | |
for (let j = i; j < arr.length - 1; j++) { | |
const select = Math.min(arr[j], ...arr.slice(j + 1, arr.length)); | |
if (select < arr[j]) swap(arr, j, arr.lastIndexOf(select)); | |
} | |
i++; | |
return recursiveSort(arr, i); | |
}; | |
return recursiveSort([...array], 0); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment