Skip to content

Instantly share code, notes, and snippets.

@dukuo
Created April 10, 2020 02:06
Show Gist options
  • Save dukuo/61c38ffaa8f91f7bb234c1087d7683c8 to your computer and use it in GitHub Desktop.
Save dukuo/61c38ffaa8f91f7bb234c1087d7683c8 to your computer and use it in GitHub Desktop.
Sorting Algorithms
const insertionSort = (arr) => {
for( let i = 1; i < arr.length; i++) {
const tmp = arr[i]
let j = i - 1
while( j >= 0 && arr[j] > tmp ) {
arr[j + 1] = arr[j]
i--
}
arr[j + 1] = tmp
}
return arr
}
const selectionSort = (arr) => {
let mi
for(let i = 0; i < arr.length; i++) {
mi = i
for(let j = i + 1; j < arr.length; j++) {
if(arr[j] < arr[mi]) {
mi = j
}
}
[arr[i], arr[mi]] = [arr[mi], arr[i]]
}
return arr
}
const genRandArr = (num) => Array.from({length: num}, () => Math.floor(Math.random() * 100))
const num = 10000
const randomList1 = genRandArr(num)
const randomList2 = genRandArr(num)
console.time("Insertion sort: ")
insertionSort(randomList1)
console.timeEnd("Insertion sort: ")
console.time("Selection sort: ")
selectionSort(randomList2)
console.timeEnd("Selection sort: ")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment