1. 程式人生 > >JS實現快速排序(2種方法)

JS實現快速排序(2種方法)

1、用i和j兩個指標


2、用一個指標判斷,大的放在右邊,小的數放在左邊

<!DOCTYPE html>
<html>
<head>
	<title>quickSort</title>
	<meta charset="utf-8"/>
	<script type="text/javascript">
	var arr=[12,20,5,16,15,1,30,45,23,9];
	var start = 0;
	var end = arr.length;
	console.log('arr:' +arr);
	function quickSort(arr,low,high){
		var key=arr[low];
		var start=low;
		var end=high;
		while(end>start){
			while(end>start&&arr[end]>=key) end--;
			if(arr[end]<=key){
				var temp = arr[end];
				arr[end]=arr[start];
				arr[start] = temp;
			}
			while(end>start&&arr[start]<=key) start++;
			if(arr[start]>=key){
				var temp = arr[start];
				arr[start]=arr[end];
				arr[end]=temp;
			}
		}
		if(start>low) quickSort(arr,low,start-1);
		if(end<high) quickSort(arr,end+1,high);
	}
	quickSort(arr,start,end);
	console.log('After arr:' +arr);
	</script>


	<script type="text/javascript">
		function sort(elements){
			if(elements.length<=1){
				return elements;
			}
			var piIndex = Math.floor(elements.length/2);//取陣列中間值
			console.log(piIndex);
			var pi = elements.splice(piIndex,1)[0];//???在中間值的地方插入元素
			var left = [];
			var right = [];
			for(var i =0;i<elements.length;i++){
				if(elements[i]<pi){
					left.push(elements[i]);
				} else {
					right.push(elements[i]);
				}
			}
			return sort(left).concat([pi],sort(right));
		}
		var elements=[12,20,5,16,15,1,30,45,23,9];
		document.write(sort(elements));
	</script>
</head>
<body>

</body>
</html>