• 【各种排序系列之】快速排序法


    基本思想:

    从待排序列中任取一个元素 (例如取第一个) 作为中心,所有比它小的元素一律前放,所有比它大的元素一律后放,形成左右两个子表。

    然后再对各子表重新选择中心元素并依此规则调整,直到每个子表的元素只剩一个。

    此时便为有序序列了。

    时间效率:O(nlogn) —因为每趟确定的元素呈指数增加

    空间效率:O(logn)—因为递归要用栈(存每层low,high和pivot)

    C语言实现:

     1 //首先定义数据类型
     2 #define MAXSIZE 20 //示例的小顺序表的最大长度
     3 typedef int KeyType; //定义关键字类型为整数类型
     4 typedef struct {
     5     KeyType key;        //关键字项
     6     InfoType otherinfo;        //其他数据项
     7 }RedType;                                //记录类型
     8 typedef struct {
     9     RedType r[MAXSIZE]+1;      //r[0]用作哨兵单元
    10     int length;                           //顺序表长度
    11 }SqList;
    12 
    13 //一趟快速排序算法
    14 int Partition(SqList &L,int low,int high){ //一趟快排
    15 r[0]=r[low];  //以子表的首记录作为支点记录,放入r[0]单元
    16 int pivotkey=r[low].key;  //取支点的关键码存入pivotkey变量
    17 while(low < high){     //从表的两端交替地向中间扫描
    18     while(low<high && r[high].key>=pivotkey )
    19     { - -high;    }
    20       r[low]=r[high];  //比支点小的记录交换到低端;
    21     while(low<high && r[low].key<=pivotkey)
    22     {  + +low;    }
    23       r[high]=r[low];   //比支点大的记录交换到高端
    24 r[low]=r[0];     //支点记录到位;
    25 return low;    //返回支点记录所在位置。
    26 }
    27 
    28 //整个快速排序的递归算法:
    29 void QSort ( SqList  &L,  int low, int high ) {
    30     if ( low < high) {
    31        pivot = Partition ( L, low, high ); ////一趟快排,将r[ ]一分为二
    32         QSort ( L, low, pivot-1); //在左子区间进行递归快排,直到长度为1
    33         QSort ( L, pivot+1, high );  //在右子区间进行递归快排,直到长度为1
    34     }
    35 }
    36 
    37 
    38 //实际中,如果对顺序表L进行快速排序的操作函数为:
    39 void QuickSort ( SqList  &L) {
    40    QSort ( L,  1,  L.length );
    41  }

    设每个子表的支点都在中间,则:

    第1趟比较,可以确定1个元素的位置;

    第2趟比较(2个子表),可以再确定2个元素的位置;

    第3趟比较(4个子表),可以再确定4个元素的位置;

    第4趟比较(8个子表),可以再确定8个元素的位置;

             ……

    只需ëlog2nû +1趟便可排好序。

  • 相关阅读:
    uvm_cookbook--sequences--wait for a signal
    Makefile目标文件搜索(VPATH和vpath
    git stash
    vuex-persist,解决vuex中的数据刷新页面之后丢失的问题
    element表格中的输入框有时会存在输入不上的情况
    简单 Linux 文件系统?
    Shell 脚本是什么?
    什么是BASH?
    如何规划一台 Linux 主机,步骤是怎样?
    什么是GUI?
  • 原文地址:https://www.cnblogs.com/4everlove/p/3393307.html
Copyright © 2020-2023  润新知