排序算法-基数排序20220413

基数排序偏向于实际业务场景使用,一般适用于字符串排序或者手机号等排序,其中字符串排序使用了ascII码作为依据,基数排序思想是逐位进行计数排序,最终得到有序的数组;一般业务来讲,我们希望的顺序是第一位字符/数字优先有序,在第一位有序的情况下再要求第二位、第三位…有序,想做到这个需求,需要我们从低位优先进行排序,一些特殊业务也可以考虑从高位优先进行排序。

而更多的时候,字符串是参差不齐的,那在排序的时候,我们可以对短的字符串,在末位补0让它和最长的一样长就可以比较了。

基数排序代码如下:

public class RadixSort {
	// ascii码总共128个,定义此常量用于创建计数排序里的那个统计数组
	public static final int ASCII_RANGE = 128;

	public static String[] radixSort(String[] array, int maxLength) {
		// 创建临时数组,用于临时存储每轮排好序的数组
		String[] sortedArray = new String[array.length];
		// 进行maxLength次计数排序,maxLength为数组里最长的那个字符串长度
		// 低位优先排序
		for (int k = maxLength - 1; k >= 0; k--) {
			int[] count = new int[ASCII_RANGE];
			for (String s : array) {
				int index = getCharIndex(s, k);
				count[index]++;
			}
			for (int i = 1; i < count.length; i++) {
				count[i] = count[i] + count[i - 1];
			}
			for (int i = array.length - 1; i >= 0; i--) {
				int index = getCharIndex(array[i], k);
				int sortedIndex = count[index] - 1;
				sortedArray[sortedIndex] = array[i];
				count[index]--;
			}
			array = sortedArray.clone();
		}
		return array;
	}

	private static int getCharIndex(String str, int k) {
		if (str.length() < k + 1) {
			return 0;
		}
		return str.charAt(k);
	}

	public static void main(String[] args) {
		String[] array = {"qd", "abc", "qwe", "hhh", "CWS", "ope"};
		System.out.println(Arrays.toString(radixSort(array, 3)));
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值