基数排序

C++

int maxbit(int data[], int n) //辅助函数，求数据的最大位数{
    int maxData = data[0];///< 最大数
    /// 先求出最大数，再求其位数，这样有原先依次每个数判断其位数，稍微优化点。
    for (int i = 1; i < n; ++i)
    {
        if (maxData < data[i])
            maxData = data[i];
    }
    int d = 1;
    int p = 10;
    while (maxData >= p)
    {
        //p *= 10; // Maybe overflow
        maxData /= 10;
        ++d;
    }
    return d;/*    int d = 1; //保存最大的位数    int p = 10;    for(int i = 0; i < n; ++i)    {        while(data[i] >= p)        {            p *= 10;            ++d;        }    }    return d;*/}void radixsort(int data[], int n) //基数排序{
    int d = maxbit(data, n);
    int *tmp = new int[n];
    int *count = new int[10]; //计数器
    int i, j, k;
    int radix = 1;
    for(i = 1; i <= d; i++) //进行d次排序
    {
        for(j = 0; j < 10; j++)
            count[j] = 0; //每次分配前清空计数器
        for(j = 0; j < n; j++)
        {
            k = (data[j] / radix) % 10; //统计每个桶中的记录数
            count[k]++;
        }
        for(j = 1; j < 10; j++)
            count[j] = count[j - 1] + count[j]; //将tmp中的位置依次分配给每个桶
        for(j = n - 1; j >= 0; j--) //将所有桶中记录依次收集到tmp中
        {
            k = (data[j] / radix) % 10;
            tmp[count[k] - 1] = data[j];
            count[k]--;
        }
        for(j = 0; j < n; j++) //将临时数组的内容复制到data中
            data[j] = tmp[j];
        radix = radix * 10;
    }
    delete []tmp;
    delete []count;}

C

#include<stdio.h>#define MAX 20//#define SHOWPASS#define BASE 10void print(int *a, int n) {
  int i;
  for (i = 0; i < n; i++) {
    printf("%d\t", a[i]);
  }}void radixsort(int *a, int n) {
  int i, b[MAX], m = a[0], exp = 1;

  for (i = 1; i < n; i++) {
    if (a[i] > m) {
      m = a[i];
    }
  }

  while (m / exp > 0) {
    int bucket[BASE] = { 0 };

    for (i = 0; i < n; i++) {
      bucket[(a[i] / exp) % BASE]++;
    }

    for (i = 1; i < BASE; i++) {
      bucket[i] += bucket[i - 1];
    }

    for (i = n - 1; i >= 0; i--) {
      b[--bucket[(a[i] / exp) % BASE]] = a[i];
    }

    for (i = 0; i < n; i++) {
      a[i] = b[i];
    }

    exp *= BASE;#ifdef SHOWPASS
    printf("\nPASS   : ");
    print(a, n);#endif
  }}int main() {
  int arr[MAX];
  int i, n;

  printf("Enter total elements (n <= %d) : ", MAX);
  scanf("%d", &n);
  n = n < MAX ? n : MAX;

  printf("Enter %d Elements : ", n);
  for (i = 0; i < n; i++) {
    scanf("%d", &arr[i]);
  }

  printf("\nARRAY  : ");
  print(&arr[0], n);

  radixsort(&arr[0], n);

  printf("\nSORTED : ");
  print(&arr[0], n);
  printf("\n");

  return 0;}

Python

#!/usr/bin/env python#encoding=utf-8import mathdef sort(a, radix=10):
    """a为整数列表， radix为基数"""
    K = int(math.ceil(math.log(max(a)+1, radix))) # 用K位数可表示任意整数
    for i in range(1, K+1): # K次循环
        bucket = [[] for j in range(radix)] # 不能用 [[]]*radix，否则相当于开了radix个完全相同的list对象
        for val in a:
            bucket[val%(radix**i)//(radix**(i-1))].append(val) # 獲得整數第K位數字 （從低到高）
        del a[:]
        for each in bucket:
            a.extend(each) # 桶合并

Lua

-- 获取表中位数local maxBit = function (tt)
    local weight = 10;      -- 十進制
    local bit = 1;
    
    for k, v in pairs(tt) do
        while v >= weight do
            weight = weight * 10;
            bit = bit + 1;  
        end
    end
    return bit;end-- 基数排序local radixSort = function (tt)
    local maxbit = maxBit(tt); 

    local bucket = {};
    local temp = {};
    local radix = 1;
    for i = 1, maxbit do
        for j = 1, 10 do
            bucket[j] = 0;      --- 清空桶
        end
        for k, v in pairs(tt) do
            local remainder = math.floor((v / radix)) % 10 + 1;    
            bucket[remainder] = bucket[remainder] + 1;      -- 每個桶數量自動增加1
        end
        
        for j = 2, 10 do
            bucket[j] = bucket[j - 1] + bucket[j];  -- 每个桶的数量 = 以前桶数量和 + 自个数量
        end 
        -- 按照桶的位置，排序--这个是桶式排序，必须使用倒序，因为排序方法是从小到大，顺序下来，会出现大的在小的上面清空。
        for k = #tt, 1, -1 do
            local remainder = math.floor((tt[k] / radix)) % 10 + 1;
            temp[bucket[remainder]] = tt[k];
            bucket[remainder] = bucket[remainder] - 1;
        end
        for k, v in pairs(temp) do
            tt[k] = v;
        end
        radix = radix * 10;
    endend;

javascript

Array.prototype.radixSort = function() {
  let arr = this.slice(0)
  const max = Math.max(...arr)
  let digit = `${max}`.length
  let start = 1
  let buckets = []
  while(digit > 0) {
    start *= 10
    for(let i = 0; i < arr.length; i++) {
      const index = arr[i] % start
      !buckets[index] && (buckets[index] = [])
      buckets[index].push(arr[i])
    }
    arr = []
    for(let i = 0; i < buckets.length; i++) {
      buckets[i] && (arr = arr.concat(buckets[i]))
    }
    buckets = []
    digit --
  }
  return arr}const arr = [1, 10, 100, 1000, 98, 67, 3, 28, 67, 888, 777]console.log(arr.radixSort())

</source>

Objective-C

1 - (NSArray*)radixSort:(NSArray *) unsortedArray { 2     NSMutableArray *tempArray; 3     NSInteger maxValue = 0; 4     NSInteger maxDigit = 0; 5     NSInteger level = 0; 6     
 7     do { 8         // 1、创建10个桶 9         NSMutableArray *buckets = [NSMutableArray array];10         for (int i = 0; i < 10; i++) {11             [buckets addObject:[NSMutableArray array]];12         }13         // 2、把数据保存到桶中14         for (int i = 0; i < unsortedArray.count; i++) {15             NSInteger elementValue = [unsortedArray[i] integerValue];16             
17             int dividend = level < 1 ? 1 : pow(10, level);18             int mod = elementValue / dividend % 10;19             [buckets[mod] addObject:unsortedArray[i]];20             
21             
22             if (maxDigit == 0) {23                 if (elementValue > maxValue) {24                     maxValue = elementValue;25                 }26             }27         }28         // 3、合并桶中的数据29         tempArray = [NSMutableArray array];30         for (int i = 0; i < buckets.count; i++) {31             [tempArray addObjectsFromArray:buckets[i]];32         }33         
34         if (maxDigit == 0) {35             while (maxValue > 0) {36                 maxValue = maxValue / 10;37                 maxDigit ++;38             }39         }40         
41         // 4、继续下一轮排序42         unsortedArray = tempArray;43         level += 1;44         
45     } while (level < maxDigit);46     
47     return tempArray;48 }

</source>

Swift

1 func radixSort(unsortedArray: [Int]) -> [Int]{ 2     var unsortedArray = unsortedArray 3     
 4     var tempArray = [Int]() 5     var maxValue = 0 6     var maxDigit = 0 7     var level = 0 8     
 9     repeat {10         var buckets = [[Int]]()11         for _ in 0..<10 {12             buckets.append([Int]())13         }14         
15         for i in 0..<unsortedArray.count {16             let elementValue = unsortedArray[i]17             
18             let divident = level < 1 ? 1 : NSDecimalNumber(decimal: pow(10, level)).intValue19             let mod = elementValue / divident % 1020             buckets[mod].append(elementValue)21             
22             if maxDigit == 0 {23                 if elementValue > maxValue {24                     maxValue = elementValue25                 }26             }27         }28         
29         tempArray.removeAll()30         for element in buckets {31             tempArray.append(contentsOf: element)32         }33         
34         if maxDigit == 0 {35             while maxValue > 0 {36                 maxValue = maxValue / 1037                 maxDigit += 138             }39         }40         
41         unsortedArray = tempArray42         level += 143         
44     } while (level < maxDigit)45     
46     return tempArray47 }48 49 let list = [21, 5, 322, 10, 623, 7111, 42, 56]50 let list1 = radixSort(unsortedArray: list)51 print(list)52 print(list1)