天天看點

基數排序-java版

  • 1. 基數排序
    • 1.1 基數排序的基本介紹
    • 1.2 基數排序的時間複雜度和空間複雜度等
  • 2. 代碼示範
  • 3. 圖檔引用

1. 基數排序

1.1 基數排序的基本介紹

桶排序的一種,是通過資料的各個位的值,将要排序的元素配置設定至某些 桶 中,已達到排序的作用

1.2 基數排序的時間複雜度和空間複雜度等

算法名稱 平均時間複雜度 最好情況 最壞情況 空間複雜度 穩定性
基數排序 O(n*k) O(n*k) O(n*k) O(n+k) 穩定

2. 代碼示範

/**
 * @author shengjk1
 * @date 2020/4/11
 */
public class RadixSort {
	public static void main(String[] args) {
//		int[] arr = {53, 3, 542, 748, 14, 214};
		int[] arr = new int[8];
		for (int i = 0; i < 8; i++) {
			arr[i] = (int) (Math.random() * 8000000);
		}
		radixSOrt(arr);
		System.out.println(Arrays.toString(arr));
	}
	
	public static void radixSOrt(int[] arr) {
		//1.得到數組中最大的數的位數
		//假設第一個數是最大的數
		int max = arr[0];
		for (int i = 1; i < arr.length; i++) {
			if (arr[i] > max) {
				max = arr[i];
			}
		}
		int maxLength = String.valueOf(max).length();
		
		
		
		/*
			定義一個二維數組,表示10個桶,每個桶就是一個一維數組
			1.二維數組包好10個一維數組
			2.為了防止放入資料時溢出,規定每個桶的大小為 arr.length
			3.基數排序是使用空間換時間的經典算法
			 */
		int[][] bucket = new int[10][arr.length];
		
		//為了記錄每個桶中實際上放了多少個資料,定義一個一維數組來記錄各個桶的每次放入
		//資料的個數
		int[] bucketElementCounts = new int[10];
		
		for (int i = 0, n = 1; i < maxLength; i++, n *= 10) {
			
			//往桶中存資料,第一次是個位,第二次是十位,依次類推
			for (int j = 0; j < arr.length; j++) {
				//取對應位置上的數
				int digitOfElement = arr[j] / n % 10;
				
				bucket[digitOfElement][bucketElementCounts[digitOfElement]] = arr[j];
				bucketElementCounts[digitOfElement]++;
			}
			//按照桶的順序取資料
			int index = 0;
			for (int k = 0; k < bucketElementCounts.length; k++) {
				//當桶中有資料
				if (bucketElementCounts[k] != 0) {
					for (int l = 0; l < bucketElementCounts[k]; l++) {
						arr[index++] = bucket[k][l];
					}
				}
				//從桶中取完資料後将其資料個數置為0
				bucketElementCounts[k] = 0;
			}
		}
	}
}
           

繼續閱讀