Last active
August 29, 2015 14:04
-
-
Save DevinXian/a9e9d4d054bad33a93ea to your computer and use it in GitHub Desktop.
QuickSort in Javascript
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
/** | |
* 快速排序--降序 | |
* 思路:每次选定一基准元素,将数组划分成大于和小于基准元素的两部分,再分别对子序列进行排序,直到子序列长度为1 | |
* 效率:O(nlog n) | |
*/ | |
function quick_sort(arr, start, end) { | |
if (!arr instanceof Array) { | |
console.log('invalid array'); | |
return; | |
} | |
var i = start, j = end + 1; | |
if (start < end) { //边界条件 | |
while (true) { //第一次划分基准元素选择arr[start] | |
do ++i; | |
while (!(arr[start] >= arr[i] || i == end)); //arr[i]比基准元素大,则++i | |
do --j; | |
while (!(arr[start] <= arr[j] || j == start)); //arr[j]比基准元素小,则--j | |
if (i < j) { //arr[i]<基准元素,arr[j]>基准元素 | |
swap(arr, i, j); | |
} else { | |
break; //break while(true) | |
} | |
} | |
swap(arr, start, j); //交换基准元素和arr[j],完成一次划分 | |
console.log('完成一次划分:' + arr); | |
quick_sort(arr, start, j - 1); | |
quick_sort(arr, j + 1, end); | |
} | |
} | |
function swap(arr, i, j) { | |
console.log('exchange: ' + arr[i] + ' <----> ' + arr[j]); | |
var tmp = arr[i]; | |
arr[i] = arr[j]; | |
arr[j] = tmp; | |
} | |
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
Example: | |
var arr = [2, 10, 1, 3, 5, 100, 8, 100000]; | |
quick_sort(arr, 0, arr.length - 2); | |
console.log(arr); | |
Result: | |
[ 100, 10, 8, 5, 3, 2, 1, 100000 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment