1. 程式人生 > >排序演算法之快速排序【java實現】

排序演算法之快速排序【java實現】

快速排序是最常用的排序演算法之一,它的平均時間複雜度是O(nlogn),但是它是一個不穩定的演算法。

步驟:

我們要找到一個基值,將小於基值的放在它的左邊,大於它的放在它的右邊。基值我們直接用陣列最左邊的值就行。每次排序會把基值放在正確的位置上,在根據這個值把陣列分成左右兩部分,在進行遞迴處理。

(很多同學剛接觸的時候會對這個基值有一定的誤解,認為這個基值是陣列的中間值,必須要選擇arr.length/2,其實這個值是隨便找的,每一次排序會把這個基值放在正確的排序位置上)

package zhgyu.sort;
/**
 * 快速排序
 * @author zhgyu
 *
 */
public class QuickSort {

	static final int SIZE = 10;
	
	
	public static void quickSort(int[] arr,int low,int high) {
		if(low < high) {
			int pivot = partition(arr,low, high);
			quickSort(arr, low, pivot-1);
			quickSort(arr, pivot+1, high);
		}
	}
	
	
	public static int partition(int[] arr, int low, int high) {
		
		int pivot = arr[low];
		while(low < high) {
			while(low < high && pivot <= arr[high])
				high--;
			arr[low] = arr[high];
			while(low < high && pivot >= arr[low])
				low++;
			arr[high] = arr[low];
		}
		
		arr[low] = pivot;
		return low;
	}
	
	
	public static void main(String[] args) {
			
		int[] arr = new int[SIZE];
		int i;
			
		for(i = 0; i < SIZE; i ++) {
			arr[i] = (int)(Math.random()*(100 + 1));
		}
		//排序前的陣列
		System.out.print("排序前的陣列:"+"\t");
		for(i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + "\t");
				
		}
		System.out.println();
		
		quickSort(arr, 0, SIZE - 1);
			
		//輸出陣列arr
		System.out.print("排序後的陣列:"+"\t");
		for(i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + "\t");
		}
		System.out.println();
	}
}