快速排序随机初始基准数

来源:互联网 发布:diamond软件下载 编辑:程序博客网 时间:2024/06/01 12:23

今天上课老师叫我们用快速排序法来随机基准值进行排序,刚开始没有明白是啥子意思,后来想了一下快速排序法的原理,思路就有了。

思想:

想法优于编码。随机基准数的下标就相当于原来partition返回的mid,只不过现在的mid计算方式是 mid=random.newInt(high-low+1);

 

package com.cqwu.test;

import java.util.Arrays;
import java.util.Random;

public class FastSort {
 public static void main(String args[]) {
  int array[] = { 49, 38, 65, 97, 76, 13, 27, 49 };
  System.out.println("排序前:");
  System.out.println(Arrays.toString(array));
  quickSort(array, 0, array.length - 1);
  System.out.println("排序后:");
  System.out.println(Arrays.toString(array));
 }

 /**
  *
  * @param arr
  *            要排序的数组
  * @param low
  *            数组中小的索引,用于向后扫描
  * @param high
  *            数组中大的索引,用于向前扫描
  */
 public static void quickSort(int arr[], int low, int high) {
  if (low < high) {
   Random random = new Random();
   int mid = random.nextInt(high - low + 1);//初始点定位了分断点
   partition(arr, mid, high);
   quickSort(arr, low, mid - 1);
   quickSort(arr, mid + 1, high);
  }
 }

 public static void partition(int array[], int low, int high) {
  // 将数组中第一个元素作为枢纽关键字,这个关键字将在本次分区过程中不变
  int pivotKey = array[low];
  System.out.println(pivotKey + "---->>>>>" + low);
  int i = low, j = high;
  if (low < high) {
   while (i < j) {
    while (i < j && array[j] >= pivotKey) {
     j--;
    }
    if (i < j) {
     array[i] = array[j];
     i++;
    }

    while (i < j && array[i] <= pivotKey) {
     i++;
    }
    if (i < j) {
     array[j] = array[i];
     j--;
    }
   }
   array[i] = pivotKey;
  }
 }
}