首页 > 编程语言 > 详细

quicksort 快速排序

时间:2018-07-06 17:14:42      阅读:132      评论:0      收藏:0      [点我收藏+]

javascript

function qsort(a, comp) {
	if (typeof comp==="undefined") {
		comp = function(a, b) {
			return a - b < 0;
		}
	}
	function _qsort(a, low, high) {
		if (!comp(low, high)) {
			return;
		}
		var first = low, 
			last = high,
			pivot = a[first];
		while (comp(first, last)) {
			while (comp(first, last) && !comp(a[last], pivot)) {
				--last;
			}
			a[first] = a[last];
			while (comp(first, last) && !comp(pivot, a[first])) {
				++first;
			}
			a[last] = a[first];
		}
		a[first] = pivot;
		_qsort(a, low, first-1);
		_qsort(a, first+1, high);
	}
	
	return _qsort(a, 0, a.length-1);
}

// quicksort
var a = [57, 68, 59, 52, 52, 72, 28, 96, 33, 24];
qsort(a);  
console.log(a); // [24, 28, 33, 52, 52, 57, 59, 68, 72, 96]

  

 

quicksort 快速排序

原文:https://www.cnblogs.com/mingzhanghui/p/9274431.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!