基数排序算法实现(Java版)

import java.util.ArrayList;

/**
 * @function:基数排序算法实现
 * */
public class RadixSort {

	// 构建一个二维数组,装载每次分配的数据
	private ArrayList[] tempList = new ArrayList[10];

	/**
	 * @function:构造方法,用于初始化RadixSort类
	 * */
	public RadixSort() {
		for (int i = 0; i < this.tempList.length; i++) {
			this.tempList[i] = new ArrayList();
		}
	}

	// 收集数据
	private String[] Collection(int length) {
		String[] a = new String[length];
		int k = 0;
		for (int i = 0; i < this.tempList.length; i++) {
			for (int j = 0; j < this.tempList[i].size(); j++) {
				a[k++] = (String) this.tempList[i].get(j);
			}
			this.tempList[i] = new ArrayList();
		}
		return a;
	}

	/**
	 * @function:分配数据
	 * @param: unsort 为需要排序的数组
	 * @param: index为需要按第几位分配
	 * */
	private void Distribution(String[] unsort, int index) {
		for (int i = 0; i < unsort.length; i++) {
			int j = Integer.parseInt(unsort[i].substring(index, index + 1));
			tempList[j].add(unsort[i]);
		}
	}

	/**
	 * @function:基数排序算法
	 * */
	public String[] radix(String[] a) {
		for (int i = 2; i >= 0; i--) {
			this.Distribution(a, i);
			a = this.Collection(a.length);
		}
		return a;
	}

	/**
	 * @function:打印数组
	 * */
	private void print(String[] a) {
		for (int i = 0; i < a.length; i++) {
			System.out.print(a[i] + " ");
		}
		System.out.println();
	}

	public static void main(String[] args) {
		RadixSort r = new RadixSort();
		String[] a = new String[] { "278", "109", "063", "930", "589", "333", "679" };
		// 打印数据
		r.print(a);
		// 基数排序
		a = r.radix(a);
		// 打印数据
		r.print(a);
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值