介绍
基数排序是一种相当快的排序算法,它用少量空间换取时间,其思想类似于桶排序,基数排序从个位开始,到十位、百位、千位、等,每次确定某一位的顺序,直到整个序列有序。
示例
以上出现,在最后的结果序列中,109比184先出队,最终的序列应该是:008、063、083、109、184、269、278、505、589、930
代码实现(Java和C)
Java实现
package test;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
public class Test {
public static int getMaxBits(int arr[]){
int bits = 1;
int maxBits = 1;
for (int i = 0; i < arr.length; i++) {
bits = 1;
int tmp = arr[i];
while((tmp/=10) != 0){
bits ++;
}
maxBits = bits>maxBits?bits:maxBits;
}
return maxBits;
}
public static void RadixSort(int arr[]){
//生成10个桶
@SuppressWarnings("unchecked")
Queue<Integer> bucket[] = new LinkedList[10];
for (int i = 0; i < bucket.length; i++) {
bucket[i] = new LinkedList<Integer>();
}
int maxBits = getMaxBits(arr);
int q = 1;
for(int i = 0; i < maxBits; i++){
q *= i==0?1:10;
//放
for (int j = 0; j < arr.length; j++) {
bucket[(arr[j] / q) % 10].offer(arr[j]);
}
//拿
int k = 0;
for (int j = 0; j < bucket.length; j++) {
Integer digit;
while((digit = bucket[j].poll()) != null){
arr[k++] = digit;
}
}
}
}
public static void main(String[] args) {
int arr[] = {4,1,2,54,46,123,231,431,765,3245,1432};
RadixSort(arr);
System.out.println(Arrays.toString(arr));
}
}
输出结果:[1, 2, 4, 46, 54, 123, 231, 431, 765, 1432, 3245]
C语言实现
#include <stdio.h>
#include <stdlib.h>
#define max 100
#define undifined 0x0fffffff
void print(int arr[],int length){
for(int i=0; i<length; i++){
printf("%d\n",arr[i]);
}
}
void swap(int arr[],int i,int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
//获取数组中最大数的位数
int getMaxBits(int arr[],int length){
int bits = 1;
int maxBits = 1;
for(int i=0; i<length; i++){
bits = 1;
int tmp = arr[i];
while(tmp/=10){
bits ++;
}
maxBits = maxBits<bits? bits:maxBits;
}
return maxBits;
}
typedef struct Queue{
int front,rear;
int data[max];
}Queue;
int isEmptyQueue(Queue * que){
if(que->rear == que->front){
return 1;
}
return 0;
}
int isFullQueue(Queue * que){
if((que->rear + 1) % max == que->front){
return 1;
}
return 0;
}
void initQueue(Queue * que){
que->front = que->rear = 0;
}
int deQueue(Queue * que,int * e){
if(!isEmptyQueue(que)){
que->front = (que->front + 1) % max;
(*e) = que->data[que->front];
return 1;
}
return 0;
}
int enQueue(Queue * que,int e){
if(!isFullQueue(que)){
que->rear = (que->rear + 1) % max;
que->data[que->rear] = e;
return 1;
}
return 0;
}
void radixSort(int arr[],int length){
Queue bucket[10];
for(int i=0; i<10;i++){
initQueue(&bucket[i]);
}
int maxBits = getMaxBits(arr,length);
int q=1;
for(int i=0; i<maxBits ;i++){
q *= i==0?1:10;
for(int j=0; j<length; j++){
int r = arr[j] / q %10;
enQueue(&bucket[r],arr[j]);
}
int k=0;
for(int j=0; j<10; j++){
int e = undifined;
while(!isEmptyQueue(&bucket[j])){
deQueue(&bucket[j],&e);
arr[k++] = e;
}
}
}
}
int main(){
int arr[] = {3,4,1,213,43,534,123,325,1,3,54,8};
radixSort(arr,12);
print(arr,12);
return 0;
}