zoukankan      html  css  js  c++  java
  • 快速排序

    基本思想

    通过使用一个基准值将列表分为2个子列表,具体的过程是:

    将基准值放在正确的位置上,在一个子列表中放入小于基准值的元素,另一个子列表中放入大于基准值的元素。

    这就是快速排序(Quick Sort)的思想。

    快排算法提供了目前已知最快的排序技术,除了某些极其特殊的情况下之外,快速排序徐几乎适用于所有场合。

    实现代码

    package com.csdhsm.sort;
    
    /** 
     * @Title: QuickSort.java
     * @Package: com.csdhsm.sort
     * @Description 快速排序
     * @author Han
     * @date 2016-4-3 上午11:37:02 
     * @version V1.0
     */ 
          
    public class QuickSort {
        
        /**
         * 快速排序递归调用
         * @Description 
         * @author Han
         * @param arr
         * @param low
         * @param high
         */
        public void sort(int[] arr,int low,int high){
            
            if(low < high){
                
                int pos = findPoss(arr,low,high);
                sort(arr,low,pos-1);
                sort(arr,pos+1,high);
            }
        }
        
         
        /** 
         * @Description 寻找合适的位置
         * @author Han
         * @param a
         * @param low
         * @param high  
         */
              
        public int findPoss(int arr[],int low,int high){
            
            /**
             * t为锚点,左边都是小于t的数字,右边都是大于t的数字
             */
            int t = arr[low];
            
            /**
             * 一直要找到low等于high为止
             */
            while(low < high){
                
                while(low < high && arr[high] >= t){
                    
                    high--;
                }
                arr[low] = arr[high];
                
                while(low <high && arr[low] <= t){
                    
                    low++;
                }
                arr[high] = arr[low];
            }
            
            arr[low] = t;
            return low;
        }
    }

    效率分析

    不稳定。

    空间复杂度:O(1)

    时间复杂度:O(nlog2n)

    最坏情况:O(n2),要排序数组基本有序,基准值每次取最大(最小)元素,退化为冒泡。

    最好情况:O(nlog2n) 基准值两边元素个数基本相同.

  • 相关阅读:
    区块链
    区块链
    区块链
    区块链
    区块链 – 介绍
    区块链 教程
    Matplotlib 直方图
    Matplotlib 饼图
    Matplotlib 柱状图
    Matplotlib 多个图形
  • 原文地址:https://www.cnblogs.com/a294098789/p/5349873.html
Copyright © 2011-2022 走看看