集册 Java实例教程 使用快速排序对数组排序

使用快速排序对数组排序

欢马劈雪     最近更新时间:2020-01-02 10:19:05

516
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用快速排序对数组排序

public class QuickSortApp

{

  public static void main(String[] args)

  {
  /* from 
  nowjava.com - 时  代  Java*/

    int LEN = 100;

    int[] unsorted = new int[LEN];

    for (int i = 0; i<LEN; i++)

      unsorted[i] = (int)(Math.random() * 100) + 1;

    System.out.println("Unsorted array:");

    printArray(unsorted);

    int[] sorted = sort(unsorted);

    System.out.println("\n\nSorted array:");

    printArray(sorted);

  }


  private static void printArray(int[] array)

  {/**时代Java - N o w  J a v a . c o m**/

    System.out.println();

    for (int i = 0; i < array.length; i++)

    {

      if (array[i] < 10)

        System.out.print(" ");

      System.out.print(array[i] + " ");

      if ((i+1) % 20 == 0)

        System.out.println();

    }

  }


  private static int[] a;


  public static int[] sort(int[] array)

  {

    a = array;

    sort(0, a.length - 1);       // sort the entire array

    return a;

  }


  public static void sort(int low, int high)

  {

    if (low >= high)

      return;

    int p = partition(low, high);

    sort (low, p);

    sort (p+1, high);

  }


  public static int partition(int low, int high)

  {

    int pivot = a[low];


    int i = low - 1;

    int j = high + 1;


    while (i < j)

    {

      for (i++; a[i] < pivot; i++);

      for (j--; a[j] > pivot; j--);

   
展开阅读全文