温习基础算法之快速排序

快速排序

基于分治的思想,采取递归的方式处理子问题

伪代码

QUICKSORT(A,p,r)
	if p
PARTITION(A,p,r)
	x = A[r]
	i = p-1
	for j = p to r-1
		if A[j] <= x
			i = i + 1
			exchange A[r] with A[j]
	exchange A[i+1] with A[r]
	return i + 1 
	

java语言实现

class Main {
    public static void main(String[] args) {
        

        int[] arr = { 2, 1, 3, 4, 5, 1, 3 };
        quickSort(arr, 0, arr.length-1);
        
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i]+",");
        }
    }

    public static void quickSort(int[] arr, int p, int r) {
        if (p < r) {
            int q = partition(arr, p, r);
            quickSort(arr, p, q - 1);
            quickSort(arr, q+1, r);
        }
    }

    public static int partition(int[] arr, int p, int r) {
        int x = arr[r];
        int i = p - 1;
        for (int j = p; j <= r - 1; j++) {
            if (arr[j] <= x) {
                i++;
                swap(arr,i,j);
            }
        }
        swap(arr, i + 1, r);
        return i + 1;
    }
    public static void swap(int[] arr, int i,int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
    
}

你可能感兴趣的:(算法)