码迷,mamicode.com
首页 > 编程语言 > 详细

排序算法

时间:2019-09-11 16:18:54      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:ios   时间复杂度   while   递归   空间   swa   排序算法   ++   argc   

 

快速排序

平均时间复杂度O(nlogn);

最好情况时间复杂度O(nlogn),pivotkey基本处于顺序表中间;

最坏情况时间复杂度O(n),顺序表处于正序和倒序;

 

最好情况空间复杂度O(logn),要执行logn次递归调用;

最坏情况空间复杂度O(n),要执行n-1次递归调用;

#include <iostream>
#include <vector>

using namespace std;

typedef struct {
    vector<int> r = {0};
    int length;
} SqList;

void swap(SqList * L, int i, int j) {
    int temp = L->r[i];
    L->r[i] = L->r[j];
    L->r[j] = temp;
}

int getPivot(SqList *L, int low, int high) {
    int pivot = L->r[low];
   
    while(low < high) {
        while(low < high && pivot <= L->r[high]) {
            high --;
        }
        swap (L, low, high);
        
        while(low < high && pivot > L->r[low]) {
            low ++;
        }
        swap (L, low, high);        
    }
    return low;
}

void QSort(SqList *L, int low, int high) {    
    if(low < high) {
        int pivot = getPivot(L, low, high);
        QSort(L, low, pivot-1);
        QSort(L, pivot+1, high);
    }
}

void QuickSort (SqList *L) {
    QSort(L, 1, L->length-1);
}

int main (int argc, char** argv) {
    SqList *sl = new SqList;
    
    int num = 0, temp = 0;
    
    cout << "cin the number of sqlist(include flag)" << endl;
    cin >> num;
    sl->length = num;
    
    for(int i = 0; i < num-1; ++i) {
        cin >> temp;
        sl->r.push_back(temp);
    }

    QuickSort(sl);
    
    for(int i = 0; i < num; ++i)
        cout << sl->r[i] << endl;
    
    return 0;
}

 

排序算法

标签:ios   时间复杂度   while   递归   空间   swa   排序算法   ++   argc   

原文地址:https://www.cnblogs.com/gdut-gordon/p/11506296.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!