Created
September 22, 2012 04:17
-
-
Save guipn/3765097 to your computer and use it in GitHub Desktop.
Simple quicksort implementations
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
// The simplest implementation I can write. | |
function qsort(array) { | |
var lower, upper, pivot; | |
if (array.length <= 1) { | |
return array; | |
} | |
pivot = array.pop(); | |
lower = array.filter(function (value) { | |
return value <= pivot; | |
}); | |
upper = array.filter(function (value) { | |
return value > pivot; | |
}); | |
return qsort(lower). | |
concat([pivot]). | |
concat(qsort(upper)); | |
} | |
// In-place, still simple. Not as readable. | |
function qsort_ip(array) { | |
function partition(array, p, q) { | |
var pivot = array[p], | |
i = p, | |
swap; | |
for (j = p + 1; j < q; j++) { | |
if (array[j] < pivot) { | |
i++; | |
swap = array[i]; | |
array[i] = array[j]; | |
array[j] = swap; | |
} | |
} | |
swap = array[p]; | |
array[p] = array[i]; | |
array[i] = swap; | |
return i; | |
} | |
function qsort_in_place(array, start, end) { | |
var pivot; | |
if (start < end) { | |
pivot = partition(array, start, end); | |
qsort_in_place(array, start, pivot); | |
qsort_in_place(array, pivot + 1, end); | |
} | |
} | |
qsort_in_place(array, 0, array.length); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice, thanks :D