[数据结构]——桶排序

一,桶排序

以下代码转自:桶排序

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. #include <iostream>    
  2.  #include <list>    
  3.      
  4.  using namespace std;    
  5.      
  6.  struct Node    
  7.  {    
  8.      double value;    
  9.      Node *next;    
  10.  };    
  11.  //桶排序主程序    
  12.  void bucketSort(double* arr, int length)    
  13.  {    
  14.      Node key[10];    
  15.      int number = 0;    
  16.      Node *p, *q;//插入节点临时变量    
  17.      int counter = 0;    
  18.      for(int i = 0; i < 10; i++)    
  19.      {    
  20.          key[i].value = 0;    
  21.          key[i].next = NULL;    
  22.      }    
  23.      
  24.      for(int i = 0; i < length; i++)    
  25.      {    
  26.          Node *insert = new Node();    
  27.          insert->value = arr[i];    
  28.          insert->next = NULL;    
  29.          number = arr[i] * 10;    
  30.          if(key[number].next == NULL)    
  31.          {    
  32.              key[number].next = insert;    
  33.          }    
  34.          else    
  35.          {    
  36.              p = &key[number];    
  37.              q = key[number].next;    
  38.              while((q != NULL) && (q->value <= arr[i]))    
  39.              {    
  40.                  q = q->next;    
  41.                  p = p->next;    
  42.              }    
  43.              insert->next = q;    
  44.              p->next = insert;    
  45.          }    
  46.      }    
  47.      for(int i = 0; i < 10; i++)    
  48.      {    
  49.          p = key[i].next;    
  50.          if(p == NULL)    
  51.              continue;    
  52.          while(p != NULL)    
  53.          {    
  54.              arr[counter++] = p->value;    
  55.              p = p->next;    
  56.          }    
  57.      }    
  58.  }    
  59.      
  60.  int main()    
  61.  {    
  62.      double a[] = {0.78, 0.17, 0.39, 0.26, 0.72, 0.94, 0.21, 0.12, 0.23, 0.68};    
  63.      bucketSort(a, 10);    
  64.      for(int i = 0; i < 10; i++)    
  65.      {    
  66.          cout << a[i] << " ";    
  67.      }    
  68.      cout << endl;    
  69.      return 0;    
  70.  }    

【例】要将一副混洗的52张扑克牌按点数A<2<…<J<Q<K排序,需设置13个"箱子",排序时依次将每张牌按点数放入相应的箱子里,然后依次将这些箱子首尾相接,就得到了按点数递增序排列的一副
一般情况下每个箱子中存放多少个关键字相同的记录是无法预料的,故箱子的类型应设计成链表为宜。

原文地址:https://www.cnblogs.com/zhiliao112/p/4237202.html