QuickSort explanation and make code by myself

QuickSort explanation and make code by myself

介紹

快速排序是基礎算法裏面非常簡單暴力的排序算法,正如他的名字一樣,排序效率高,在最差的情況下,時間複雜度爲O(n2),雖然其他排序也有很多在O(n2),但是遇到數據量龐大的時候選擇快速排序是沒錯的。正好今天學到快速排序,讓我想到了學習排序算法的第一課—冒泡排序,而快速排序就是冒泡排序的改進版。
在這裏插入圖片描述
上圖中可以看出快速排序的平均情況比冒泡排序的平均情況要好。

圖解

在這裏插入圖片描述
通過圖解可以很好的瞭解到快速排序的原理。(這只是我個人理解,如果有問題請指出)

代碼

public class QuickSort {
	
	public static void main(String[] args){
		int [] quickData = {7, 3, 9, 5, 4, 1, 2, 6, 8, 11, 55, 88, 54, 32, 45, 18, 111, 214, 784, 21, 456, 120, 666};
		
		quickData = quickSort(quickData, 0, quickData.length - 1);
		
		for(int i = 0; i < quickData.length; i++){
			System.out.println(quickData[i]);
		}
	}
	
	private static int[] quickSort(int[] transBefore, int low, int height){
		if(low > height){
			return null;
		}
		
		int pivotIndex = getMiddle(transBefore, low, height);
		
//		System.out.println("中間數" + transBefore[pivotIndex]);
		
		quickSort(transBefore, low, pivotIndex - 1);
		quickSort(transBefore, pivotIndex + 1, height);
		
		return transBefore;
	}
	
	private static int getMiddle(int[] transBefore, int low, int height){
		int pivot = transBefore[low];
		boolean direction = true;//從右到左
		int temp;
		while(low < height){
			if(direction){
				if(pivot > transBefore[height]){
					
					transBefore[low] = transBefore[height];
					direction = false;
					low++;
				}
				else{
					height--;
				}
			}else{
				if(pivot < transBefore[low]){
					
					transBefore[height] = transBefore[low];
					direction = true;
					height--;
				}else{
					low++;
				}
			}
		}
		transBefore[height] = pivot;
		return height; //low
	}
}

總結

快速排序採用分治法的思想來實現快速排序的,分治法顧名思義就是分而治之,將複雜的問題分爲若干個簡單的問題,從而逐個擊破,達到理想的效果。好了,總的來說,快速排序的關鍵點是需要知道基準的作用、移動方向的轉變條件以及遞歸的使用。

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