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: 每次取最大或者最小值

     

  • 相关阅读:
    洛谷 P1886 滑动窗口(单调队列)
    POJ 2559 Largest Rectangle in a Histogram(单调栈)
    eclipse开发velocity实例(初学)
    Spring MVC 教程,快速入门,深入分析
    传智博客(JavaWeb方面的所有知识)听课记录(经典)
    JSP/SERVLET入门教程--Servlet 使用入门
    javaweb入门实例---servlet例子
    Eclipse快捷键大全(转载)
    简单java web应用程序搭建与部署
    Servlet 工作原理解析
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8449202.html
Copyright © 2011-2022 走看看