Created
May 13, 2018 14:54
-
-
Save martianyi/ea7f91f04c4c6fdadcaff1aba4d267e1 to your computer and use it in GitHub Desktop.
JS sort algorithm
This file contains hidden or 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 bubbleSort(arr) { | |
for (var i = 0; i < arr.length - 1; i++) { | |
for (var j = 0; j < arr.length - 1 - i; j++) { | |
if (arr[j] > arr[j+1]) { | |
var temp = arr[j]; | |
arr[j] = arr[j+1]; | |
arr[j+1] = temp; | |
} | |
} | |
} | |
return arr; | |
} |
This file contains hidden or 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 insertSort (arr) { | |
for (var i = 1; i < arr.length; i++) { | |
var temp = arr[i]; | |
var prev = i - 1; | |
while (temp < arr[prev] && prev >= 0) { | |
arr[prev + 1] = arr[prev]; | |
arr[prev] = temp; | |
prev--; | |
} | |
} | |
return arr; | |
} |
This file contains hidden or 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(arr) { | |
if (arr.length < 2) return arr; | |
var pivotIndex = Math.floor(arr.length / 2); | |
var pivot = arr.splice(pivotIndex, 1); | |
var left = [], | |
right = []; | |
for (var i = 0; i < arr.length; i++) { | |
if (arr[i] < pivot) { | |
left.push(arr[i]); | |
} else { | |
right.push(arr[i]); | |
} | |
} | |
return quickSort(left).concat(pivot, quickSort(right)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment