算法实现/排序/基数排序

维基教科书,自由的教学读本
跳到导航 跳到搜索

Java[编辑]

public class RadixSort {
    
    public static void radixSort(int []a) {

        if (null == a || 0 == a.length) return;
        int k = maxbit(a);
        int radix = 1;
        for (int i = 0; i < k; i++) {
            countingSort(a, radix);
            radix *= 10;
        }
    }

    private static int maxbit(int []a) {
        int max = a[0];
        for (int i = 1; i < a.length; i++) max = max < a[i]? a[i] : max;
        int d = 1;
        while ((max=max/10) > 0) d++;
        return d;
    }

    public static void countingSort(int []a, int radix) {

        int[] counts = new int[10];
        int len = a.length;
        int[] buffer = new int[len];

        for (int i = 0; i < len; i++) counts[ ( a[i] / radix ) % 10]++;
        for (int i = 1; i < counts.length; i++) counts[i] = counts[i] + counts[i-1];

        for (int i = len - 1; i >= 0; i--) {
            buffer[counts[ ( a[i] / radix ) % 10] - 1] = a[i];
            counts[( a[i] / radix ) % 10] = counts[( a[i] / radix ) % 10] - 1;
        }

        for (int i = 0; i < len; i++) a[i] = buffer[i];

    }

    public static void main(String[] args) {
        int[] a = new int[]{9,10,7,8,1,2,3,4};
        radixSort(a);

        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }

}

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 10

void 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-8

import math
def 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;
    end
end;

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())

Objective-C[编辑]

- (NSArray*)radixSort:(NSArray *) unsortedArray {
    NSMutableArray *tempArray;
    NSInteger maxValue = 0;
    NSInteger maxDigit = 0;
    NSInteger level = 0;
    
    do {
        // 1、创建10个桶
        NSMutableArray *buckets = [NSMutableArray array];
        for (int i = 0; i < 10; i++) {
            [buckets addObject:[NSMutableArray array]];
        }
        // 2、把数据保存到桶中
        for (int i = 0; i < unsortedArray.count; i++) {
            NSInteger elementValue = [unsortedArray[i] integerValue];
            
            int dividend = level < 1 ? 1 : pow(10, level);
            int mod = elementValue / dividend % 10;
            [buckets[mod] addObject:unsortedArray[i]];
            
            
            if (maxDigit == 0) {
                if (elementValue > maxValue) {
                    maxValue = elementValue;
                }
            }
        }
        // 3、合并桶中的数据
        tempArray = [NSMutableArray array];
        for (int i = 0; i < buckets.count; i++) {
            [tempArray addObjectsFromArray:buckets[i]];
        }
        
        if (maxDigit == 0) {
            while (maxValue > 0) {
                maxValue = maxValue / 10;
                maxDigit ++;
            }
        }
        
        // 4、继续下一轮排序
        unsortedArray = tempArray;
        level += 1;
        
    } while (level < maxDigit);
    
    return tempArray;
}

Swift[编辑]

func radixSort(unsortedArray: [Int]) -> [Int]{
    var unsortedArray = unsortedArray
    
    var tempArray = [Int]()
    var maxValue = 0
    var maxDigit = 0
    var level = 0
    
    repeat {
        var buckets = [[Int]]()
        for _ in 0..<10 {
            buckets.append([Int]())
        }
        
        for i in 0..<unsortedArray.count {
            let elementValue = unsortedArray[i]
            
            let divident = level < 1 ? 1 : NSDecimalNumber(decimal: pow(10, level)).intValue
            let mod = elementValue / divident % 10
            buckets[mod].append(elementValue)
            
            if maxDigit == 0 {
                if elementValue > maxValue {
                    maxValue = elementValue
                }
            }
        }
        
        tempArray.removeAll()
        for element in buckets {
            tempArray.append(contentsOf: element)
        }
        
        if maxDigit == 0 {
            while maxValue > 0 {
                maxValue = maxValue / 10
                maxDigit += 1
            }
        }
        
        unsortedArray = tempArray
        level += 1
        
    } while (level < maxDigit)
    
    return tempArray
}

let list = [21, 5, 322, 10, 623, 7111, 42, 56]
let list1 = radixSort(unsortedArray: list)
print(list)
print(list1)