zoukankan      html  css  js  c++  java
  • Quick Sort

    /*  two known area:
    * [0, leftIndex) < pivotValue; (rightIndex, right] >= pivotValue
    * [leftIndex, rightIndex] is the unknown area
    * */
    public class QuickSort {
    static Random random = new Random() ;
    public static void main(String[] args){
    int[] array = {1,9,8,5,3};
    sortIntegers(array);
    print(array);
    }
    private static void sortIntegers(int[] arr){
    if (arr == null || arr.length ==0) return;
    quickSort(arr, 0 , arr.length-1);
    }

    private static void quickSort(int[] array, int left, int right) {
    if (left>=right) return;
    int pivotPos = partition(array, left, right);
    quickSort(array, left, pivotPos-1);
    quickSort(array, pivotPos +1 , right);
    }
    //leftIndex is the 1st pos value >= pivotValue
    private static int partition(int[] array, int left, int right) {
    int pivotIndex = left + random.nextInt(right - left + 1 ) ;
    int pivotValue = array[pivotIndex];
    //change pivot value to the right
    swap(array,pivotIndex,right);
    int leftIndex = left;
    int rightIndex = right-1;//since the pivot on right no need to be included
    while(leftIndex<=rightIndex){
    if (array[leftIndex]<pivotValue){
    leftIndex++ ;
    }
    else if (array[rightIndex]>=pivotValue){
    rightIndex--;
    } else {
    //same
    //swap(array, leftIndex++,rightIndex--);
    swap(array, leftIndex,rightIndex);
    leftIndex++;
    rightIndex--;
    }
    }
    //change pivot from the right to the correct position
    swap(array,leftIndex,right);
    return leftIndex ;
    }

    private static void swap(int[] array, int pivotIndex, int right) {
    int temp = array[pivotIndex] ;
    array[pivotIndex] = array[right];
    array[right] = temp ;
    }
    public static void print(int[] array){
    for (int i = 0; i < array.length; i++) {
    System.out.println(array[i]);
    }
    }
    }
     

     时间复杂度, 空间复杂度 

    average: nlogn : logn 层 每层 n 次排序

              n

       n/2     n/2 

     n/4 n/4   n/4  n/4 

    worst: 每次取最大或者最小值

     

  • 相关阅读:
    java内部类
    重新回顾JSP
    vs 链接动态库 (不用放在可执行文件同一目录)
    c++ 文件夹读取文件
    为人处世
    Windows常用软件
    windows好用的软件
    冒泡排序,快速排序,归并排序
    最大公约数、最小公倍数、所有约数
    linux U盘 硬盘 unable to mount
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8449202.html
Copyright © 2011-2022 走看看