📜  适用于QuickSort的Java程序

📅  最后修改于: 2021-04-28 13:53:24             🧑  作者: Mango

像合并排序一样,QuickSort是一种分而治之算法。它选择一个元素作为枢轴,并围绕拾取的枢轴对给定的数组进行分区。 quickSort有许多不同的版本,它们以不同的方式选择枢轴。

  1. 始终选择第一个元素作为枢轴。
  2. 始终选择最后一个元素作为枢轴(在下面实现)
  3. 选择一个随机元素作为枢轴。
  4. 选择中位数作为枢轴。

quickSort中的关键过程是partition()。分区的目标是,给定一个数组和一个数组元素x作为枢轴,将x放在排序数组中的正确位置,并将所有较小的元素(小于x)放在x之前,并将所有较大的元素(大于x)放在之后X。所有这些都应在线性时间内完成。
递归QuickSort函数的伪代码:

/* low  --> Starting index,  high  --> Ending index */
quickSort(arr[], low, high)
{
    if (low < high)
    {
        /* pi is partitioning index, arr[p] is now
           at right place */
        pi = partition(arr, low, high);

        quickSort(arr, low, pi - 1);  // Before pi
        quickSort(arr, pi + 1, high); // After pi
    }
}
// Java program for implementation of QuickSort
class QuickSort
{
    /* This function takes last element as pivot,
       places the pivot element at its correct
       position in sorted array, and places all
       smaller (smaller than pivot) to left of
       pivot and all greater elements to right
       of pivot */
    int partition(int arr[], int low, int high)
    {
        int pivot = arr[high]; 
        int i = (low-1); // index of smaller element
        for (int j=low; j Array to be sorted,
      low  --> Starting index,
      high  --> Ending index */
    void sort(int arr[], int low, int high)
    {
        if (low < high)
        {
            /* pi is partitioning index, arr[pi] is 
              now at right place */
            int pi = partition(arr, low, high);
  
            // Recursively sort elements before
            // partition and after partition
            sort(arr, low, pi-1);
            sort(arr, pi+1, high);
        }
    }
  
    /* A utility function to print array of size n */
    static void printArray(int arr[])
    {
        int n = arr.length;
        for (int i=0; i

请参阅有关QuickSort的完整文章以了解更多详细信息!