排序算法 Sorting Algorithm(二)

算法课老师在讲分治时的一个例子,还提到了其他很多经典算法,这周统一总结一下。

  • 快速排序(QUICK-SORT)
QUICK-SORT(A, p, r)
	if p<r
		then q <-PATITION(A, p, r)
		QUICK-SORT(A, p, q)
		QUICK-SORT(A, q+1, r)

QUICK-SORT (A, n)

PARTITION(A, p ,r)
	if r < p 
		then return -1;
	if r = p
		then return r 
	x<-A[p]
	i<-p+1
	j<-r
	while i<j
		do  if A[i]<x
				then i++;			
		    if A[j]>x
			    then j--;
			if i<j              |>即将出while循环时
				then exchange A[i]<->A[j]
	exchange A[p]<->A[i]
	return i
	

最坏情况:每次PARTITION找中间位置时都在最左或最右 O(n^2)
平均情况:O(nlogn)

JAVA:

import java.util.Arrays;

public class QuickSort{
	public static void main(String[] args){
		int[] A = {4,2,5,1,3,6,9,7,8};
		System.out.println(Arrays.toString(A));  
		quickSort(A,9);	
		System.out.println(Arrays.toString(A)); 
	}
	public static void quickSort(int[] A, int n){
		if(n<=0) return;
		quickSort(A,0,n-1);
	}
	private static void quickSort(int[] A,int left, int right){
		if(left<right) { 
			int p = partition(A,left,right);
			quickSort(A,left,p-1);
			quickSort(A,p+1,right);
		}
	}
	private static int partition(int[] A,int left,int right){
		
		int x = A[right];
		int i = left - 1;

		for(int j = left; j<right ;j++) {
			if(A[j] < x) {
				i++;
				int temp = A[i];
				A[i] = A[j];
				A[j] = temp;
			}
		}
		int temp = A[i + 1];
		A[i + 1] = A[right];
		A[right] = temp;
		return i + 1;
	}
}
}

猜你喜欢

转载自blog.csdn.net/u013453787/article/details/82665689