您的位置:首页 > 其它

排序算法之基数排序

2017-04-28 10:07 204 查看
阅读目录
1、基本思想
2、代码示例
3、效率分析

回到目录


1、基本思想

  将所有待比较数值(正整数)统一为同样 的数位长度,数位较短的数前面补零。然后,从最低位开始,依次进行一次排序。这样从最低位排序一直到最高位排序完成以后,数列就变成一个有序序列。
回到目录


2、代码示例

package sort;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

/**
* 基数排序
*/

public class RadixSort {

@Test
public void TestSort() {
int a[] = { 49, 38, 65, 97, 76, 13, 27, 49, 78, 53, 51 };
sort(a,2);
}

public void sort(int[] arr) {
int len=arr.length;
// 首先确定排序的趟数;
int max = arr[0];
for (int i = 1; i < len; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
int time = 0;
// 判断位数;
while (max > 0) {
max /= 10;
time++;
}
// 建立10个队列;
List<ArrayList> queue = new ArrayList<ArrayList>();
for (int i = 0; i < 10; i++) {
ArrayList<Integer> queue1 = new ArrayList<Integer>();
queue.add(queue1);
}
// 进行time次分配和收集;
for (int i = 0; i < time; i++) {
// 分配数组元素;
for (int j = 0; j < len; j++) {
// 得到数字的第time+1位数;
int x = arr[j] % (int) Math.pow(10, i + 1)
/ (int) Math.pow(10, i);
ArrayList<Integer> queue2 = queue.get(x);
queue2.add(arr[j]);
queue.set(x, queue2);
}
int count = 0;// 元素计数器;
// 收集队列元素;
for (int k = 0; k < 10; k++) {
while (queue.get(k).size() > 0) {
ArrayList<Integer> queue3 = queue.get(k);
arr[count] = queue3.get(0);
queue3.remove(0);
count++;
}
}
}
for (int i = 0; i < len; i++){
System.out.print(arr[i]+" ");
}

}

public void sort(int[] arr, int d) //d表示最大的数有多少位
{
int len=arr.length;
int k = 0;
int n = 1;
int m = 1; //控制键值排序依据在哪一位
int[][]temp = new int[10][len]; //数组的第一维表示可能的余数0-9
int[]order = new int[10]; //数组orderp[i]用来表示该位是i的数的个数
while(m <= d)
{
for(int i = 0; i < len; i++)
{
int lsd = ((arr[i] / n) % 10);
temp[lsd][order[lsd]] = arr[i];
order[lsd]++;
}
for(int i = 0; i < 10; i++)
{
if(order[i] != 0)
for(int j = 0; j < order[i]; j++)
{
arr[k] = temp[i][j];
k++;
}
order[i] = 0;
}
n *= 10;
k = 0;
m++;
}
for (int i = 0; i < len; i++){
System.out.print(arr[i]+" ");
}
}

}


回到目录


3、效率分析

 

出处:http://hehaiyang.cnblogs.com/
本博客内容主要以学习、研究和分享为主,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: