Created
May 16, 2014 21:30
-
-
Save jwchang0206/baa00041977e1622a6cb to your computer and use it in GitHub Desktop.
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
'use strict'; | |
var arr = [6, 5, 3, 1, 8, 7, 2, 4]; | |
function partition(arr, lp, rp) { | |
var middle = Math.floor((lp + rp) / 2), | |
pivot = arr[middle], | |
temp; | |
while (lp <= rp) { | |
while (arr[lp] < pivot) lp++; | |
while (arr[rp] > pivot) rp--; | |
if (lp <= rp) { | |
temp = arr[lp]; | |
arr[lp] = arr[rp]; | |
arr[rp] = temp; | |
lp++; | |
rp--; | |
} | |
} | |
return lp; | |
} | |
function quickSort(arr, lp, rp) { | |
var index; | |
lp = lp || 0; | |
rp = rp || arr.length - 1; | |
if (arr.length > 1) { | |
index = partition(arr, lp, rp); | |
if (lp < index - 1) | |
quickSort(arr, lp, index - 1); | |
if (index < rp) | |
quickSort(arr, index, rp); | |
} | |
return arr; | |
} | |
console.log(quickSort(arr)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment