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

    一、概念

    快速排序是对冒泡排序的一种改进:记录的比较和移动是从两端向中间进行的,关键码较大的记录一次就能从前面移动到后面,关键码较小的记录一次就能从后面移动到前面,记录移动的距离较远,从而减少了总的比较次数和移动次数。

    基本思想:首先选取一个轴值(povit,即比较的基准),将待排序记录划分为独立的两部分,左侧记录的关键码均小于或等于轴值,右侧记录的关键码均大于轴值,然后分别对两部分重复上述过程,直到整个序列有序,即简单的分而治之思想。

    二、复杂度

    排序方法   最差时间分析  最好时间分析  平均时间复杂度  空间复杂度  稳定性
     快速排序  O(n2)  O(nlog2n)  O(nlog2n)  O(log2n)-O(n)  不稳定

    三、代码实现

     1 package sort;
     2 
     3 public class QuickSort {
     4     static int count = 1;
     5     public static int partition(int[] array,int low, int high){
     6         //选取轴值
     7         int key = array[low];
     8         while(low < high){
     9             //从后往前扫描
    10             while(array[high] >= key && low < high){
    11                 high--;
    12             }
    13             //此时key > array[high],需要移动到key的左边
    14             array[low] = array[high];
    15             //从前往后扫描
    16             while(array[low] <= key && low < high){
    17                 low++;
    18             }
    19             array[high] = array[low];
    20         }
    21         array[high] = key;//此时low == high
    22         printArray(array,count++);
    23         return high;
    24     }
    25     public void quicksort(int[] array, int low, int high){
    26         if(low >= high)
    27             return;
    28         int index = partition(array, low, high);
    29         quicksort(array,low,index-1);
    30         quicksort(array,index+1,high);
    31         
    32     }
    33     //打印每次排序的结果
    34         public static void printArray(int a[],int count){
    35             if(count != 0)
    36             System.out.print("第" + count + "次   ");
    37             for(int m = 0; m < a.length; m++){
    38                 System.out.print(a[m] + " ");
    39             }
    40             System.out.println();
    41         }
    42         public static void main(String[] args) {
    43             QuickSort ms = new QuickSort();
    44             int array[] = {7, 2, 8, 3, 1, 6, 9, 0, 5, 4};
    45             ms.quicksort(array, 0, array.length-1);
    46         }
    47 }

    冒泡排序

    选择排序

    堆排序

    插入排序

    希尔排序(缩小增量排序)

    归并排序-递归实现

    基数排序

  • 相关阅读:
    生产者消费者模型
    查看网络通不通的几种方法
    tomcat在45秒内没有启动,启动超时
    request获取各种路径
    修改web项目发布路径
    web.xml不同版本的头
    Web.xml 错误或异常页面配置
    ModelAndView command
    java初始化顺序
    初始化时的过程
  • 原文地址:https://www.cnblogs.com/fankongkong/p/7230667.html
Copyright © 2011-2022 走看看