快速排序

使用分治思想:

  分解:数组A[p..r]被划分成两个(可能为空)子数组A[p..q-1]和A[q+1..r],使得A[p..q-1]中的每一个元都小于等于A[q],而A[q]也小于等于A[q+1..r]中的每个元素。其中,计算下标q也是计划过程的一部分。

  解决:通过递归调用快速排序,对于数组A[p..q-1]和A[q+1..r]进行排序。

  合并:因为子数组都是原地址排序的,所以不需要合并操作:数组A[p..r]已经有序

在PARTITION函数中,设置个n值,用来记录快速排序排完所需要比较的次数。

import java.util.Random;

public class Question3 {
    private static int n = 0; //比较次数计数值
    public static void main(String[] args)
    {

        int[] A = new int[10];
        //求10个具有相同值数组快排的比较次数
        int[] A1={5,5,5,5,5,5,5,5,5,5};
        //10个顺序的比较次数
        int[] A2={1,2,3,4,5,6,7,8,9,10};
        //10个逆序的比较次数
        int[] A3={10,9,8,7,6,5,4,3,2,1};
        Random random = new Random();
        for (int i=0; i<10; i++)
            A[i] = random.nextInt(10);
        System.out.println("快速排序前(数组随机生成):");
        for (int i=0; i<10; i++)
        {
            System.out.print(A[i]);
            System.out.print(' ');
        }
        System.out.print('
');
        quickSort(A3,0,9);
        for(int i = 0;i<10;i++)
        {
            System.out.print(A[i]);
            System.out.print(" ");
        }
        //System.out.println("
n记录的比较次数:");
        //System.out.println(n);

    }

    public static void quickSort(int[] array) {
        if (array != null) {
            quickSort(array, 0, array.length - 1);
        }
    }

    private static void quickSort(int[] A, int p, int r) {
        if (p >= r || A == null)
            return;
        int q = partition(A, p, r);
        quickSort(A, p, q - 1);
        quickSort(A, q + 1, r);
    }

    private static int partition(int[] A,int p,int r)
    {
        int x = A[r];
        int i = p-1;
        for(int j=p; j<r; j++)
        {
            if(A[j]<=x)
            {
                n++;
                i++;
                int temp = A[i];
                A[i] = A[j];
                A[j] = temp;
            }
        }
        int temp = A[i+1];
        A[i+1] = A[r];
        A[r] = temp;
        return i+1;
    }

}
原文地址:https://www.cnblogs.com/dear_diary/p/6929900.html