• 9.桶排序


    #include <iostream>
    #include <cmath>
    #include <algorithm>
    using namespace std;
    
    const int maxn = 100 + 2;
    int num[maxn], n;
    
    struct node
    {
        node(){ next = NULL; num = -1; }
        node(int x, node *n):num(x), next(n) {}
        int num;
        node *next;
    };
    
    int bits(int x)
    {
        int ret = 0;
        
        while(x >= 10)
        { ret++; x /= 10; }
        
        return ret + 1;
    }
    
    void Insert(node *n, int x)
    {
        node *p = n;
    /*
    if(p->next == NULL) { p->next = new node(x, NULL); return ; } */这一部分完全没必要写 for(; p->next != NULL; p = p->next) { if(p->next->num > x) { p->next = new node(x, p->next); return ; } } p->next = new node(x, NULL); } void Bucket_sort(int *num, int n, int k) { node *c = new node[10]; for(int i = 0; i < n; i++) Insert(&c[num[i] / k], num[i]); int t = 0; for(int i = 0; i < 10; i++) for(node *p = c[i].next; p != NULL; p = p->next) num[t++] = p->num; } int main() { cin >> n; int *k = &num[0]; for(int i = 0; i < n; i++) { cin >> num[i]; if(*k < num[i]) k = &num[i]; } Bucket_sort(num, n, pow(10, bits(*k) - 1)); for(int i = 1; i < n; i++) cout << num[i] << " "; cout << endl; }

    时间复杂度为O(n) ~ O(n^2), 嗯, 比较随缘的一种算法

    我的这个版本只能排序正数,对数据分布均匀的情况比较适用

    代码没有快排来的简洁, 只是学习用吧....

    再有就当作练习链表了....

  • 相关阅读:
    sharepoint JQ获取List列表的值
    微信修改域名回掉
    input设置只读
    MVC-AJAX-JSON
    sharepoint添加子网站
    sharepoint打开解决方案库
    前台获取参数值
    SQL查看表结构以及表说明
    JQ获取对象属性值
    bootstrap table样式
  • 原文地址:https://www.cnblogs.com/QQ-1615160629/p/5860494.html
Copyright © 2020-2023  润新知