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);
        }
    }
  • 相关阅读:
    用Python实现多核心并行计算
    Sublime Text 中文乱码
    Python_pickle
    New blog
    git Bash常用命令
    用TTS实现文本转语音
    bc#54 div2
    用Python制作新浪微博爬虫
    hdu5000 背包dp
    mac下配置Qt for Android+iOS
  • 原文地址:https://www.cnblogs.com/kachunyippp/p/10256278.html
Copyright © 2011-2022 走看看