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), 嗯, 比较随缘的一种算法

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

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

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