zoukankan      html  css  js  c++  java
  • 基数排序

    "次位优先"LSD (Least sgnificant digital)基数排序动图演示
     

     
     
     1 #include <iostream>
     2 #include <queue>
     3 #include <list>
     4 
     5 using namespace std;
     6 
     7 // 求出数组a中最大的位数,即求出最大的数字的位数
     8 int getDigit(int a[], int n)
     9 {
    10     // 先找出数组中最大的那个数 
    11     int Max = -1;
    12     for(int i = 0; i < n; ++i) 
    13     {
    14         if(a[i] > Max)
    15             Max = a[i];
    16     }
    17     int k = 1;
    18     // 再求这个最大的数有几位 
    19     while(Max/10 > 0)
    20     {
    21         k++;    // k表示最大的数字的位数 
    22         Max /= 10; 
    23     }
    24     
    25     return k;
    26 }
    27 
    28 // 正整数的基数排序 
    29 // n表示待排数组a中元素的个数
    30 void radixSort(int a[], int n)
    31 {    
    32     
    33     int k = getDigit(a, n); 
    34     // 这里list也可以用queue代替 
    35     list<int> L[10];
    36     int r = 10;
    37     while(k--)
    38     {
    39         for(int i = 0; i < n; ++i)
    40         {
    41             // 把数放入对应的链表下面 
    42             // 比如取出个位数,即有a[i]%10/1,取出十位数,即有a[i]%100/10
    43             // 因此可以得到下面的公式 
    44             int p = (a[i]%r) / (r/10);
    45             L[p].push_back(a[i]);
    46         }
    47         
    48         
    49         int j = 0;
    50         // 把链表上的数字重新分配回原数组a,同时链表也被清空 
    51         for(int i = 0; i < 10; ++i)
    52         {
    53             while(!L[i].empty())
    54             {
    55                 a[j++] = L[i].front();
    56                 L[i].pop_front();
    57             }
    58         } 
    59             
    60         r = r * 10;
    61     }
    62         
    63 } 
    64 
    65 
    66 int main()
    67 {
    68     int n;
    69     int a[100010];
    70     while (cin >> n)
    71     {
    72         for(int i = 0; i < n; ++i)
    73             cin >> a[i];
    74         radixSort(a, n);
    75         for(int i = 0; i < n; ++i)
    76         {
    77             cout << a[i] << ' ';
    78         }  
    79         cout << endl;
    80     }
    81 
    82     return 0;
    83 }
     
  • 相关阅读:
    tzoj5855: 数据结构实验:最短路(SPFA)
    tzoj5779 最短路(SPFA模板)
    洛谷P3375 【模板】KMP字符串匹配(KMP)
    poj2533 The Bottom of a Graph(Tarjan+缩点)
    poj1236 Network of Schools(Tarjan+缩点)
    危险道路(Tarjan+割边/桥)
    前端开发中的浏览器兼容性问题总结
    递归应用示例
    统计单词数
    找素数的两种方法
  • 原文地址:https://www.cnblogs.com/FengZeng666/p/12523856.html
Copyright © 2011-2022 走看看