各种排序

来源:互联网 发布:photoshop cc mac下载 编辑:程序博客网 时间:2024/05/19 22:02
#include<iostream>


using namespace std;




void swap(int *a, int *b){
    int tmp = *a;
    *a = *b;
    *b = tmp;
}


// insert sort o(n^2)
void insert_sort(int list[], int n){
    for(int i = 1; i < n; ++i){
        for(int j = i; j > 0; --j){
            if(list[j] < list[j-1]){
                swap(list[j], list[j-1]);
            }
        }
    }
}


// o(n^2)
void buttle_sort(int list[], int n){
    for(int i = 0; i < n; ++i){
        for(int j = 0; j < n-i-i; ++j){
            if(list[j+1] < list[j]){
                swap(list[j+1], list[j]);
            }
        }
    }
}
//优化后冒泡排序
void abutter_buttle_sort(int list[], int n){
    int last = n;
    while(last > 0){
        int i = 0;
        for(; i < last - 1; ++i){
            if(list[i] > list[i+1]){
                swap(list[i], list[i+1]);
            }
        }
        last = i;
    }
}


// quick_sort
int once_sort(int list[], int l, int r){
    int first = l;
    int end = r;
    //默认中间值mid 就是first
    while(first < end){
        //右侧值必须大于mid
        while(first < end && list[first] <= list[end]){
            --end;
        }
        //退出循环说明:右侧值找到比mid小的值,需要交换
        if(first < end){
            swap(list[first], list[end]);
        }
        while(first < end && list[first] < list[end]){
            ++first;
        }
        //退出循环说明:左侧值找到比mid大的值,需要交换
        if(first < end){
            swap(list[first], list[end]);
        }
        
    }
    return first;
}


// o(nlogn)
void quick_sort(int list[], int l, int r){
    if(list == NULL || l < 0 || r < 0 || l >= r){
        return;
    }
    int mid = once_sort(list, l, r);
    quick_sort(list, l, mid - 1);
    quick_sort(list, mid + 1, r);
}


//heap o(nlgN)
void heap_once_sort(int list[], int root, int n){
    int child = 2*root + 1;
    if(child < n){
        int rchild = child + 1;
        if(rchild < n && list[rchild] > list[child]){
            child = rchild;
        }
        if(list[root] < list[child]){
            swap(list[root], list[child]);
            heap_once_sort(list, child, n - root);
        }
    }
}
void heap_sort(int list[], int n){
    for(int i = n/2 - 1; i >= 0; --i){
        heap_once_sort(list, i, n);
    }
    for(int i = n -1 ; i>=1; --i){
        swap(list[i], list[0]);
        heap_once_sort(list, 0, i);
    }
}
int main(){
    int list[5] = {2,6,1,4,7};
    //insert_sort(list, 5);
    //buttle_sort(list, 5);
    //abutter_buttle_sort(list, 5);
    //quick_sort(list, 0, 4);
    heap_sort(list, 5);
    for(int i = 0; i < 5; ++i){
        cout << list[i] << " ";
    }
    cout << endl;


    return 0;
}
0 0
原创粉丝点击