一,桶排序
以下代码转自:桶排序
- #include <iostream>
- #include <list>
- using namespace std;
- struct Node
- {
- double value;
- Node *next;
- };
- //桶排序主程序
- void bucketSort(double* arr, int length)
- {
- Node key[10];
- int number = 0;
- Node *p, *q;//插入节点临时变量
- int counter = 0;
- for(int i = 0; i < 10; i++)
- {
- key[i].value = 0;
- key[i].next = NULL;
- }
- for(int i = 0; i < length; i++)
- {
- Node *insert = new Node();
- insert->value = arr[i];
- insert->next = NULL;
- number = arr[i] * 10;
- if(key[number].next == NULL)
- {
- key[number].next = insert;
- }
- else
- {
- p = &key[number];
- q = key[number].next;
- while((q != NULL) && (q->value <= arr[i]))
- {
- q = q->next;
- p = p->next;
- }
- insert->next = q;
- p->next = insert;
- }
- }
- for(int i = 0; i < 10; i++)
- {
- p = key[i].next;
- if(p == NULL)
- continue;
- while(p != NULL)
- {
- arr[counter++] = p->value;
- p = p->next;
- }
- }
- }
- int main()
- {
- double a[] = {0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68};
- bucketSort(a, 10);
- for(int i = 0; i < 10; i++)
- {
- cout << a[i] << " ";
- }
- cout << endl;
- return 0;
- }
【例】要将一副混洗的52张扑克牌按点数A<2<…<J<Q<K排序,需设置13个"箱子",排序时依次将每张牌按点数放入相应的箱子里,然后依次将这些箱子首尾相接,就得到了按点数递增序排列的一副
一般情况下每个箱子中存放多少个关键字相同的记录是无法预料的,故箱子的类型应设计成链表为宜。