HOME/Articles/

6种排序算法总结

Article Outline

整理一下各种排序算法。

class Sort{
public:
    //冒泡排序,O(N*N)
    void bubbo_sort(vector<int>& arr){
        for(int i=0;i<arr.size()-1;i++){
            for(int j=arr.size()-1;j>i;j--){
               if(arr[j]<arr[j-1]) swap(arr[j],arr[j-1]);
            }
        }
    }
    //直接插入排序,O(N*N)
    void insert_sort(vector<int> &arr){
        for(int i = 1;i < arr.size();i++){
            int key = arr[i];
            int j = i;
            while(j>0&&arr[j-1]>key){
                arr[j] = arr[j-1];
                j--;
            }
            arr[j] = key;
        }
    }
    //选择排序,O(N*N)
    void select_sort(vector<int> &arr){
        for(int i=0;i<arr.size();i++){
            int minVal = arr[i];
            int minPos = i;
            for(int j=i+1;j<arr.size();j++){
                if(minVal>arr[j]){
                    minVal = arr[j];
                    minPos = j;
                }
            }
            swap(arr[i],arr[minPos]);
        }
    }
    //快速排序,O(N*LogN)
    void quick_sort(vector<int> & arr,int l,int r){
        if(l>=r) return ;
        int i = l,j = r,key = arr[l];
        while(i<j){
            while(i < j && arr[j] > key) j--;
            if(i < j) arr[i++] = arr[j];
            while(i < j && arr[i] < key) i++;
            if(i < j) arr[j--] = arr[i];
        }
        arr[i] = key;
        quick_sort(arr,l,i-1);
        quick_sort(arr,i+1,r);
    }
    //归并排序,O(N*LogN)
    void merge_sort(vector<int> &arr,int l,int r){
        vector<int> tmp(r-l+1);
        if(l>=r) return ;
        int mid = (l+r) / 2;
        merge_sort(arr,l,mid);
        merge_sort(arr,mid+1,r);
        int i = l,j = mid+1;
        int k = 0;
        while(i<=mid&&j<=r){
            if(arr[i]<arr[j])
                tmp[k++] = arr[i++];
            else
                tmp[k++] = arr[j++];
        }
        while(i<=mid){
            tmp[k++] = arr[i++];
        }
        while(j<=r){
            tmp[k++] = arr[j++];
        }
        for(int i=0;i<=r-l;i++){
            arr[l+i] = tmp[i];
        }
    }

    void shiftDown(vector<int>& arr,int index,int heapSize){
        int key = arr[index];
        int father = index,child;
        while((child=father*2+1)<heapSize){
            if(child+1<heapSize && arr[child] < arr[child+1]) child++;
            if(key > arr[child]) break;
            arr[father] = arr[child];
            father = child;
        }
        arr[father] = key;
    }
    //堆排序,O(N*LogN)
    void heap_sort(vector<int> &arr){
        //construct max heap
        for(int i=arr.size()/2-1;i>=0;i--){
            shiftDown(arr,i,arr.size());
        }
//        for(int i=0;i<arr.size();i++){
//            cout<<arr[i]<<" ";
//        }
//        cout<<endl;
        for(int i=arr.size()-1;i>=0;i--){
            swap(arr[0],arr[i]);
            shiftDown(arr,0,i);
        }
    }
};