快速排序(比希爾排序會快穩定一點)

百度百科:

https://baike.baidu.com/item/%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F%E7%AE%97%E6%B3%95/369842?fromtitle=%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F&fromid=2084344&fr=aladdin

 

示意圖:

 

代碼:

package com.afmobi;

import static org.hamcrest.CoreMatchers.instanceOf;

import java.util.Arrays;

import org.apache.commons.lang3.ArrayUtils;

public class QuickSort {

	public static void main(String[] args) {
		int[] arr = { -9,78,0,23,-567,70 };
		QuickSort.quickSort(arr,0,arr.length -1 );
		System.out.println("arr:" + Arrays.toString(arr));
	}

	public static void quickSort(int[] arr,int left,int right) {
		int l = left;
		int r = right;
		
		int pivot = arr[(left + right)/2]; //中軸值
		int temp = 0;
		
		// 循環的目的是讓比pivot值小的數全部放到左邊
		while (l < r) {
			// 在pivot的左邊一直找,找到大於pivot的數才退出
			while (arr[l] < pivot) {
				l++;
			}
			// 在pivot的右邊一直找,找到小於pivot的數才退出
			while (arr[r] > pivot) {
				r--;
			}
			
			if (l >= r) { // pivot左邊全是<pivot的數,pivot右邊全是>pivot的數,
				break;
			}
			
			//交換
			temp = arr[l];
			arr[l] = arr[r];
			arr[r] = temp;
			
			// 如果交換完arr[l] = pivot,那就不必要比右邊了;
			if (arr[l] == pivot) {
				r--;
			}
			//同理
			if (arr[r] == pivot) {
				l++;
			} 
			
		}
		//注意:如果l == r 必須l++,r-- 否則遞歸調用,會棧溢出
		if (l == r) {
			l++;
			r--;
		}
		
		//向左遞歸
		if (left < r) {
			quickSort(arr, left, r);
		}
		
		if (right > l) {
			quickSort(arr, l, right);
		}
		
	}
}

測試結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章