Created
January 22, 2019 04:21
-
-
Save userkang/d2796faaf1c5f870b49e8c7488879fd4 to your computer and use it in GitHub Desktop.
js 快速排序
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) { | |
// 交换元素 | |
function swap(arr, a, b) { | |
var temp = arr[a]; | |
arr[a] = arr[b]; | |
arr[b] = temp; | |
} | |
function partition(arr, left, right) { | |
var pivot = arr[left]; | |
var storeIndex = left; | |
for (var i = left + 1; i <= right; i++) { | |
if (arr[i] < pivot) { | |
swap(arr, ++storeIndex, i); | |
} | |
} | |
swap(arr, left, storeIndex); | |
return storeIndex; | |
} | |
function sort(arr, left, right) { | |
if (left < right) { | |
var storeIndex = partition(arr, left, right); | |
sort(arr, left, storeIndex - 1); | |
sort(arr, storeIndex + 1, right); | |
} | |
} | |
sort(arr, 0, arr.length - 1); | |
return arr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment