快排

package TestCode;

public class QuickSort {
	public void quickSort(int[] arr, int low, int high) {
		if (low < high) {
			int index = getIndex(arr, low, high);

			quickSort(arr, low, index);
			quickSort(arr, index + 1, high);
		}
	}

	public int getIndex(int[] arr, int low, int high) {
		int tmp = arr[low];// 基準數據

		while (low < high) {
			// 當隊尾的元素大於等於基準數據時,向前挪動high指針
			while (low < high && arr[high] >= tmp) {
				high--;
			}
			// 如果隊尾元素小於tmp了,需要將其賦值給low
			arr[low] = arr[high];
			// 當隊首元素小於等於tmp時,向前挪動low指針
			while (low < high && arr[low] <= tmp) {
				low++;
			}
			// 當隊首元素大於tmp時,需要將其賦值給high
			arr[high] = arr[low];
		}
		arr[low] = tmp;
		
		return low;
	}
	public static void main(String[] args) {
		int[] arr={5,9,10,2,5,1,6,18,26,45,22};
		QuickSort quick=new QuickSort();
		quick.quickSort(arr, 0, arr.length-1);
		for(int num:arr){
			System.out.print(num+" ");
		}
	}
}

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