快速排序(js实现)
function Quicksort(a) { Qsort(a, 0, a.length - 1); return a; } function Qsort(a, low, high) { var pivot; if (low < high) { pivot = Partition(a, low, high); Qsort(a, low, pivot - 1); Qsort(a, pivot+1, high); } } function Partition(a, low, high) { var temp; var pivotKey; pivotKey = a[low]; while (low < high) { while (low < high && a[high] >= pivotKey) high--; temp = a[high]; a[high] = a[low]; a[low] = temp; while (low < high && a[low] <= pivotKey) low++; temp = a[low]; a[low] = a[high]; a[high] = temp; } return low; }测试:
function getRandom() { var count = 15; var random; var a = new Array(); while (count--) { random = Math.floor(Math.random() * 1000); a.push(random); } return a; }结果:
快速排序的算法思想最好还是看看数据结构的相关书籍吧,我这里只是简单的说下。快速排序就是冒泡排序的升级版本,实现思想就是预先设置一个所谓的中间量(piovtkey),从low和height两个方向往中间走,完成把比piovtkey大的放右边,小的放左边。
function Partition(a, low, high) { var temp; var pivotKey; pivotKey = a[low]; while (low < high) { while (low < high && a[high] >= pivotKey) high--; temp = a[high]; a[high] = a[low]; a[low] = temp; while (low < high && a[low] <= pivotKey) low++; temp = a[low]; a[low] = a[high]; a[high] = temp; } return low; }
然后在递归调用.
if (low < high) { pivot = Partition(a, low, high); Qsort(a, low, pivot - 1); Qsort(a, pivot+1, high); }
原文地址:http://blog.csdn.net/u014209090/article/details/45013569