实现快速排序算法的 Java 程序

要理解此示例,您应该具备以下 Java 编程的知识:

Java 中的快速排序

快速排序算法基于分治法,其中通过选择一个枢轴元素将数组划分为子数组。

在划分数组时,枢轴元素的放置方式应使小于枢轴的元素保留在左侧,大于枢轴的元素保留在右侧。

对左右子阵列继续相同的过程。最后,排序的元素被组合起来形成一个排序的数组。

要了解更多信息,请访问快速排序算法

示例:实现快速排序算法的 Java 程序

import java.util.Arrays;

public class Quicksort {

  // method to find the partition position
  static int partition(int array[], int low, int high) {

    // choose the rightmost element as pivot
    int pivot = array[high];

    // pointer for greater element
    int i = (low - 1);

    // traverse through all elements
    // compare each element with pivot
    for (int j = low; j < high; j++) {
      if (array[j] <= pivot) {

        // if element smaller than pivot is found
        // swap it with the greater element pointed by i
        i++;

        // swapping element at i with element at j
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
      }

    }

    // swapt the pivot element with the greater element specified by i
    int temp = array[i + 1];
    array[i + 1] = array[high];
    array[high] = temp;

    // return the position from where partition is done
    return (i + 1);
  }

  static void quickSort(int array[], int low, int high) {
    if (low < high) {

      // find pivot element such that
      // elements smaller than pivot are on the left
      // elements greater than pivot are on the right
      int pi = partition(array, low, high);

      // recursive call on the left of pivot
      quickSort(array, low, pi - 1);

      // recursive call on the right of pivot
      quickSort(array, pi + 1, high);
    }
  }
}

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

    int[] data = { 8, 7, 2, 1, 0, 9, 6 };
    System.out.println("Unsorted Array");
    System.out.println(Arrays.toString(data));

    int size = data.length;

    // call quicksort() on array data
    Quicksort.quickSort(data, 0, size - 1);

    System.out.println("Sorted Array in Ascending Order ");
    System.out.println(Arrays.toString(data));
  }
}

输出

Unsorted Array
[8, 7, 2, 1, 0, 9, 6]
Sorted Array in Ascending Order
[0, 1, 2, 6, 7, 8, 9]

在这里,数组的元素按升序排序。如果我们想按降序对元素进行排序,那么在 for 循环内部,我们可以将代码更改为:

// the less than sign is changed to greater than
if (array[j] >= pivot) {