Created
January 12, 2021 15:26
-
-
Save thedewpoint/53625215b4ce5fc0ba3e6963ab7a98dc to your computer and use it in GitHub Desktop.
different sorting algorithms implemented in JS
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 test = [5,6,1,7,7,7,7,3,5,2,2,9,9,0,9]; | |
const insertionSort = (arr)=>{ | |
for(let i = 1; i < arr.length; i++){ | |
let current = arr[i]; | |
let j = i-1; | |
while(j >=0 && arr[j] > current) { | |
arr[j+1] = arr[j] | |
j--; | |
} | |
arr[j+1] = current; | |
} | |
return arr; | |
}; | |
const quickSort = (arr) =>{ | |
if(arr.length < 1) return arr; | |
const [pivot,...rest] = arr; | |
const left = [], right = []; | |
for (let i = 0; i < rest.length; i++) { | |
if(rest[i] < pivot) left.push(rest[i]); | |
else right.push(rest[i]); | |
} | |
return quickSort(left).concat(pivot).concat(quickSort(right)); | |
}; | |
const mergeSort = (arr) => { | |
if(arr.length<=1) return arr; | |
const middle = Math.floor(arr.length/2); | |
const left = mergeSort(arr.slice(0,middle)); | |
const right = mergeSort(arr.slice(middle)); | |
const result = []; | |
while(right.length && left.length) { | |
if(left[0] < right[0]){ | |
result.push(left.shift()); | |
} else { | |
result.push(right.shift()); | |
} | |
} | |
return result.concat(left).concat(right); | |
}; | |
console.log(insertionSort(test.slice())) | |
console.log(quickSort(test.slice())); | |
console.log(mergeSort(test.slice())); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment