浅谈排序算法之基数排序(8)

基数排序(radix sort)是一种用于卡片排序机上的算法。对待排序数组A,算法先按最低有效位来进行排序,即首先根据所有元素的个位上的值进行排序,然后再根据十位上的值进行排序,直至超过数组中最大元素的宽度。为了确保基数排序算法的正确性,一位数排序算法必须是稳定的,即若两个数的某一位上的值一样,那么排序后这两个数的相对位置也不能发生改变。
基数排序只是一种策略,并没有给出具体的代码实现,其伪代码如下:

Radix_Sort(A, d)
	for i=1 to d
		use a stable sort to sort array A on digit i

这里就产生了一个问题,一位数排序算法怎么选择???以计数排序作为中间稳定排序算法的基数排序不是原址排序,而其他的比较排序算法是原址排序。因此,若硬件空间优先,则倾向于原址排序算法。本文选择优化后的冒泡排序作为一位数中间稳定排序算法实现。
示例代码如下:

package org.vimist.pro.Algorithm.Sort;

import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.Random;

/**
 * An demonstration of {@code RadixSort}.
 *
 * @author Mr.K
 */
public class RadixSort {

    public static void main(String[] args) {
        int N = 20;
        int[] arr = new int[N];
        Random random = new Random();
        for (int i = 0; i < arr.length; i++) {
            arr[i] = random.nextInt(150);
        }
        System.out.println("待排序数组: " + Arrays.toString(arr));
        Radix_Sort(arr);
        System.out.println("已排序数组: " + Arrays.toString(arr));
    }

    /**
     * Accepts an array and sorts the array by {@code RadixSort}. When
     * {@code RadixSort} is implemented, a stable sort must be used to
     * ensure that result is correct. {@code BubbleSort} is an easy sort
     * although it may have large complexity in terms of stability.
     *
     * @param arr specified array to be sorted
     */
    private static void Radix_Sort(@NotNull int[] arr) {
        for (int i = 1; i <= 3; i++) {
            _Bubble_Sort(arr, i);
        }
    }

    /**
     * A process of <em>Bubble-Sort</em>.
     *
     * @param arr   specified array
     * @param digit index to be used when sorting
     */
    private static void _Bubble_Sort(@NotNull int[] arr, @NotNull int digit) {
        int m = (int) Math.pow(10, digit), n = m / 10;
        for (int i = 0; i < arr.length; i++) {
            boolean isExchanged = false;
            for (int j = 0; j < arr.length - i - 1; j++) {
                if (arr[j] % m / n > arr[j + 1] % m / n) {
                    int num = arr[j] ^ arr[j + 1];
                    arr[j] = num ^ arr[j];
                    arr[j + 1] = num ^ arr[j + 1];
                    isExchanged = true;
                }
            }
            if (!isExchanged) {
                break;
            }
        }
    }

}

运行结果如下:

待排序数组: [84, 140, 98, 60, 28, 116, 80, 53, 12, 84, 46, 2, 38, 41, 94, 136, 18, 10, 106, 35]
已排序数组: [2, 10, 12, 18, 28, 35, 38, 41, 46, 53, 60, 80, 84, 84, 94, 98, 106, 116, 136, 140]
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值