当前位置: 代码迷 >> 综合 >> 排序---基数排序
  详细解决方案

排序---基数排序

热度:42   发布时间:2023-12-05 07:38:03.0

 

import java.sql.Array;
import java.util.*;
// 1:无需package
// 2: 类名必须Main, 不可修改public class Main {public static void main(String[] args) {Scanner input = new Scanner(System.in);int n = input.nextInt();int[] arr = new int[n];for (int i = 0; i < n; i++) {arr[i] = input.nextInt();}cardinalitySort(arr);System.out.println(Arrays.toString(arr));}public static void cardinalitySort(int[] arr){List<Integer>[] lists = new List[10];for(int i =0 ;i<10;i++){lists[i] = new ArrayList<>();}int n = arr.length;int max = 0;for(int i =0;i<n;i++){max = Math.max(arr[i],max);}int count = 0;while(max!=0){max/=10;count++;}int sishu = 1;for(int i =0;i<count;i++){for(int j = 0;j<n;j++){int temp = arr[j]/sishu;lists[temp%10].add(arr[j]);}for(int j =0,index =0;j<10;j++){for(int k = 0;k<lists[j].size();k++){arr[index++] = lists[j].get(k);}}for(int j = 0;j<10;j++)lists[j].clear();sishu*=10;}}
}