boss直聘|算法 | Java 常见排序算法(纯代码)( 四 )


public void bucketSort(int[
nums){    int max = Integer.MIN_VALUE;    int min = Integer.MAX_VALUE;    for(int num : nums){
       max = Math.max(max num);
       min = Math.min(min num);
       int bucketCount = (max-min)/nums.length+1;
   List<List<Integer>> bucketList = new ArrayList<>();    for (int i = 0; i < bucketCount; i++) {
       bucketList.add(new ArrayList<>());
       for(int num : nums){        int index = (num-min)/nums.length;
       bucketList.get(index).add(num);
       for(List<Integer> bucket : bucketList){
       Collections.sort(bucket);
       int j = 0;    for(List<Integer> bucket : bucketList){        for(int num : bucket){
           nums[j
= num;
           j++;
       
   


10. 基数排序按个、十、百位依次归类排序;
public  void radixSort(int[
nums){    int min = Integer.MAX_VALUE;    int max = Integer.MIN_VALUE;    for (int num : nums) {
       min = Math.min(min num);
       max = Math.max(max num);
       for (int i = 0; i < nums.length; i++) {
       nums[i
-= min;
   
   max -= min;    int maxLen = (max+\"\").length();    int[
[
bucket = new int[nums.length
[10
;    int[
bucketCount = new int[10
;    for (int i = 0 n = 1; i < maxLen; i++ n*=10) {        for (int num : nums) {            int digitVal = num / n % 10;
           bucket[bucketCount[digitVal

[digitVal
= num;
           bucketCount[digitVal
++;
               int index = 0;        for (int j = 0; j < bucketCount.length; j++) {            if(bucketCount[j
> 0){                for (int k = 0; k < bucketCount[j
; k++) {
                   nums[index
= bucket[k
[j
;
                   index++;
               
           
           bucketCount[j
= 0;
       
       for (int i = 0; i < nums.length; i++) {
       nums[i
+= min;
   


11. 使用集合或 API11.1 优先队列public void priorityQueueSort(int[
nums){
   PriorityQueue<Integer> queue = new PriorityQueue<>();    for(int num : nums){        queue.offer(num);
       for (int i = 0; i < nums.length; i++) {
       nums[i
= queue.poll();
   


11.2 Java APIpublic void arraysApiSort(int[
nums){
   Arrays.sort(nums);