java計數排序法

參考文章:https://www.jianshu.com/p/a2f47d9037f4, 向作者表示感謝。

代碼如下: 

import java.util.Arrays;

public class CountSort {
    public static void countSort(int[] data){
        int max = getMax(data);
        System.out.println("max number: "+max);
        int[] countArr = new int[max+1];
        int length = data.length;
        int[] sortedArr = new int[length];
        // 統計每一個元素出現的次數
        for(int i=0; i<length; i++){
            countArr[data[i]]++;
        }
        // 計算每一個元素之前有多個元素,由此確定每一個元素在有序數組中的位置
        // 體現出計數排序法的思想:
        // 每個元素在有序數組中的位置是通計算確定的,而不是通過比較
        for(int i=1; i<countArr.length; i++){
            countArr[i] = countArr[i] + countArr[i-1];
        }
        for(int i=0; i<length; i++){
            sortedArr[--countArr[data[i]]] = data[i];
        }
        System.arraycopy(sortedArr, 0, data, 0, length);
        System.out.println("sortedArr: "+ Arrays.toString(sortedArr));
    }

    private static int getMax(int[] data){
        int maxIndex = 0;
        int length = data.length;
        for(int i=0; i<length; i++){
            if(data[maxIndex] < data[i]){
                maxIndex = i;
            }
        }
        return data[maxIndex];
    }
}

 

 

1.以最大的數據構建統計元素次數的數組,    int[] countArr = new int[max+1];
2.統計每一個元素出現的次數      
     for(int i=0; i<length; i++){    
        countArr[data[i]]++; 
    }
3.計算每一個元素之前有多個元素,由此確定每一個元素在有序數組中的位置體現出計數排序法的思想:
每個元素在有序數組中的位置是通計數確定的,而不是通過比較大小
              for(int i=1; i<countArr.length; i++){  
                countArr[i] = countArr[i] + countArr[i-1];
            }
按照統計次數對數據進行排序,將有序數據放入sortedArr中
        for(int i=0; i<length; i++){
            sortedArr[--countArr[data[i]]] = data[i];
        }
	分析: data[i]爲countArr數組對應的index
	    countArr[i]爲數組sortedArr的index
	    由以上兩步確定data[i]在數組sortedArr中的位置,將data[i]值賦給該位置的元素
	思想分兩步: 找到data[i]在數組sortedArr中的位置:sortedArr[--countArr[data[i]]]
	        將data[i]值賦給該位置的元素:sortedArr[--countArr[data[i]]] = data[i];
	

 

發佈了39 篇原創文章 · 獲贊 9 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章