zoukankan      html  css  js  c++  java
  • 排序算法-C++实现

    一、快速排序

    1.1 双指针实现

    #include<iostream>
    #include<vector>
    #include<utility>
    using namespace std;
    int split(vector<int>& a,int left,int right) {
      int provit = a[left];
      int index = left;
      while(left < right) {
        while(left < right && a[right] >= provit) {
          right --; // this will find the small one from the right
        }
        while(left < right && a[left] <= provit) {
          left ++; // this will find the large one from the left
        }
        if(left != right) {
          swap(a[left],a[right]); // swap the small and large
        }
      }
      swap(a[index],a[left]); // swap provit to the correct position
      return left;
    }
    void quickSort(vector<int>& a,int left,int right) {
      if(left < right) {
        int index = split(a,left,right);
        quickSort(a,left,index-1);
        quickSort(a,index+1,right);
      }
    }
    int main() {
      vector<int> a = {5,7,9,1,6,5};
      quickSort(a,0,a.size()-1);
      for(int i = 0; i < a.size();i++) {
        cout << a[i] << " ";
      }
      cout << endl;
      return 0;
    }
    

    1.2 for循环实现

    #include<iostream>
    #include<vector>
    #include<utility>
    using namespace std;
    int partition(vector<int>& array,int left,int right) {
      int provit = array[left];
      int index = left;
      swap(array[left],array[right]);
      for(int i = left;i < right;i++) {
        if(array[i] <= provit) {
          swap(array[index++],array[i]);
        }
      }
      swap(array[index],array[right]);
      return index;
    }
    void quickSort(vector<int>& array,int left,int right) {
      if(left < right) {
        int i = partition(array,left,right);
        quickSort(array, left, i-1);
        quickSort(array, i+1, right);
      }
    }
    
    int main(){
      vector<int> array = {5,8,7,6,5,9};
      quickSort(array,0,array.size()-1);
      for(int i=0;i<array.size();i++) {
        cout << array[i] << " ";
      }
      cout << endl;
      return 0;
    }
    

    复杂度分析

    时间复杂度

    快速排序的时间复杂度是O(nlogn), 详细分析见快速排序算法的时间复杂度分析[详解Master method]以及快速排序 及其时间复杂度和空间复杂度

    空间复杂度

    首先就地快速排序使用的空间是O(1)的,也就是个常数级;而真正消耗空间的就是递归调用了,因为每次递归就要保持一些数据;
    最优的情况下空间复杂度为:O(logn);每一次都平分数组
    最差的情况下空间复杂度为:O(n);退化为冒泡排序

  • 相关阅读:
    ERROR: Cannot set priority of registrydns process 33740
    Hbase和Phoenix部署-单机版
    ambari安装hdp时,新建的ambari-hdp-1.repo中baseurl无值
    centos7.2升级openssh到8.0
    kafka一个broker挂掉无法写入
    对cdh搭建过程错误总结及解决方法
    streamsets
    [Spark]Task not serializable
    [Kafka]How to Clean Topic data
    Postgresql Master/Slaver
  • 原文地址:https://www.cnblogs.com/ttxs69/p/13745378.html
Copyright © 2011-2022 走看看