排序演算法 - 快速排序

b9x_發表於2018-03-11

快速排序很重要,接觸很多次了。平均時間複雜度O(nlogn),最壞情況(有序時)O(n*n)。

優化:1.遞迴到小陣列時採用插入排序(希爾排序)。2.在切分元素上做優化


package com.zx.sort;

import java.util.Arrays;

public class Partition {
	
	public static void main(String[] args) {
		int[] a={9,1,3,6,5,55,6,63,32};
		sort(a, 0, a.length-1);
		System.out.println(Arrays.toString(a));
	}
	
	public static int partition(int[] a,int low,int high){
		int keng=low;
		int x = a[low];
		while(low<high){
			while(low<high && x<=a[high]){
				high--;
			}
			if(low<high){
				a[low++] = a[high];
			}
			while(low<high && x>a[low]){
				low++;
			}
			if(low<high){
				a[high--]=a[low];
			}
		}
		a[low]=x;
		return low;
	}
	
	public static void sort(int[] a,int low,int high){
		if (low >=high) {
			return;
		}
		int index=partition(a, low, high);
		sort(a, low, index);
		sort(a, index+1, high);
	}
}


相關文章