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

    算法复杂度:$O(nlogn)$ (递归为$O(logn)$)
    快速排序算法当序列中元素的排列比较随机时效率最高,但是当序列中元素接近有序时,会达到最坏时间复杂度$O(n^2)$,产生这种情况的主要原因在于主元没有把当前区间划分为两个长度接近的子区间。因此我们应该随机选择主元或者取中间的数据作为主元,这样期望时间复杂度对于任意输入数据都为$O(nlogn)$。

    #include <iostream>
    #include <ctime>
    #include <cstdlib> 
    #include <algorithm>
    
    using namespace std;
    
    int box[10]={89,23,56,4,2,8,9,98,25,66};
    
    int partition(int left,int right)
    {
        srand((unsigned)time(NULL));
        int p = round(1.0*rand()/RAND_MAX*(right-left)+left);
        swap(box[p],box[left]);
        int temp = box[left];
        while(left<right)
        {
            while(left<right && box[right]>temp)
            {
                --right;
            }
            box[left]=box[right];
            while(left<right && box[left]<=temp)
            {
                ++left;
            }
            box[right]=box[left];
        }
        box[left]=temp;
        return left;
    }
    
    void qsort(int left,int right)
    {
        if(left<right)
        {
            int pos = partition(left,right);
            qsort(left,pos-1);
            qsort(pos+1,right);
        }
    }
  • 相关阅读:
    ###MySQL 数据库DataBase
    操作mysql数据库
    发送邮件
    模块-os.system的两个模块/random模块/datetime模块/写日志
    map/fileter
    日期相关-时间模块
    内置函数
    集合+函数
    函数-变量-参数-递归
    模块(os模块)
  • 原文地址:https://www.cnblogs.com/kachunyippp/p/10256278.html
Copyright © 2011-2022 走看看