Last active
September 10, 2018 19:57
-
-
Save condef5/b482cf67386ae408e82d83dcd1deb841 to your computer and use it in GitHub Desktop.
Algorithms of sorting methods
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
function mergeSort(array) { | |
if (array.length > 2) { | |
let half = parseInt(array.length/2); | |
let [left, rigth] = [mergeSort(array.slice(0, half)), mergeSort(array.slice(half))]; | |
let ret = []; | |
for (let i = 0; i < array.length;i++) { | |
if (left.length <= 0 || (rigth.length > 0 && left[0] > rigth[0])) | |
ret.push(rigth.shift()); | |
else | |
ret.push(left.shift()); | |
} | |
return ret; | |
} | |
else if (array.length > 1 && array[0] > array[1]) | |
return [array[1], array[0]]; | |
else | |
return array; | |
} | |
// mergeSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]) |
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
function quickSort(array) { | |
if (array.length <= 1 ) return array; | |
let pivot = array[0], | |
i = 0; | |
for(let j = 0; j< array.length - 1; j++) { | |
if(array[j+1] < pivot) { | |
[array[j + 1], array[i+1]] = [array[i+1], array[j+1]]; | |
i++; | |
} | |
} | |
[array[0], array[i]] = [array[i], array[0]]; | |
let firstPart = quickSort(array.slice(0,i)); | |
let secondPart = quickSort(array.slice(i + 1)); | |
firstPart.push(array[i]); | |
return firstPart.concat(secondPart); | |
} | |
// quickSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment