排序—快速排序

快速排序由C.A.R.Hoare(1962) 开发的,该算法在数组中选择一个称为主元(pivot)的元素,将数组分为两部分,是的第一部分中的所有元素都小于或等于主元,而第二部分的所有元素都大于主元。对第一部分递归地应用快速排序算法,然后对第二部分递归地应用快速排序算法。

 

package ss.sort;
/**
 * 快速排序
 * @author zhangss 2016-5-3 11:42:32
 * */
public class QuickSort {
	
	public static void quickSort(int[] list){
		quickSort(list, 0, list.length - 1);
	}
	
	private static void quickSort(int[] list, int first, int last){
		if(last > first){
			int pivotIndex = partition(list, first, last);
			quickSort(list, first, pivotIndex - 1);
			quickSort(list, pivotIndex + 1, last);
		}
	}
	
	private static int partition(int[] list, int first, int last){
		int pivot = list[first];  // Choose the first element as the pivot
		int low = first + 1;      // Index for forward search
		int high = last;          // Index for backward search
		
		while(high > low){
			// Search forward from left
			while(low <= high && list[low] <= pivot)
				low++;
			
			// Search forward from right
			while(low <= high && list[high] > pivot)
				high--;
			
			// Swap two elements in the list
			if(high > low){
				int temp = list[high];
				list[high] = list[low];
				list[low] = temp;
			}
		}
		
		while(high > first && list[high] >= pivot)
			high--;
		
		// Swap pivot with list[high]
		if(pivot > list[high]){
			list[first] = list[high];
			list[high] = pivot;
			return high;
		}else{
			return first;
		}
	}
	/**
	 * A test method
	 */
	public static void main(String[] args) {
		int[] list = {2, 3, 2, 5, 6, 1, -2, 3, 14, 12};
		quickSort(list);
		for(int i = 0; i < list.length; i++)
			System.out.print(list[i] + " ");
	}

}

  

posted @ 2016-05-03 12:08  xiaoss  阅读(239)  评论(0编辑  收藏  举报