基數排序(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]