DS_【非比較排序】

Java_【非比較排序】
(1)計數排序
計數排序的思想體現在分配和收集 與比較排序不同非比較排序不用去比較各個數字之間的大小直接利用數組的特性去存儲,數組本就可以存放數據取數組的下標從小到大依然有序。所以我們直接利用數組的特性
整個分配過程相當於 我們在手裏拿到一堆無序的撲克牌然後我們按照地上所標記的數字依次將拿到的牌放置其中最後在從地上依次拿起那麼這組牌就會有序
排序過程描述
在這裏插入圖片描述
1.準備一個與原來數組A最大值與最小值差值的數組 tem
2.然後依次從待排序數組中拿取數字
3.將拿到的數字按照A數組下標進行存放用來計數
在這裏插入圖片描述
4.然後將tem中的數字進行轉化 將tem[i] 轉化爲小於等於i元素的個數
在這裏插入圖片描述
爲什麼要去這樣做 因爲這裏剛好有一個逆思維我們實際上存放數字順序的是數組tem的下標而數組tem[i]存放的值表示當前等於下標值得個數然而 只要求出 之前的小於等於i的值就能拿到下標在有序數組中的位置
5.對比原來無序數組 從後向前拿到的數字就是tem的存放的數值所對應的的下標就是數組A[i]在有序數組中該有的位置
在這裏插入圖片描述
注意:在這裏存放數據時tem[arr[i]-m] 用來表示在tem中存放的位置 -m保證在tem中存儲從0開始 不浪費存儲空間
排序算法描述
1.準備一個過度數組tem 大小爲數組A最大值與最小值的差+1
2.第一次遍歷找到A中元素並且將個數累計存放在tem中
3.第二次遍歷 先將 tem[i]的值存入item 表示個數循環item-- 將tem的下標按照item存入arr中 最後 arr就是排好的數組
代碼實現

public static void main(String[] args) {
    int[] A = {8,4,5,7,1,3,6,2};
    countSort(A,1,8);
    System.out.println(Arrays.toString(A));
}
public static void countSort(int[] arr,int m,int n){
    int len = arr.length;
    int[] tem = new int[n-m+1];
    for(int i=0;i<len;i++){
        tem[arr[i]-m]++;
    }
    for(int i=0,index=0;i<tem.length;i++){
        int item = tem[i];
        while(item--!=0){
            arr[index++]=i+m;
        }
    }
}

(2)基數排序
基數排序的實質時 在排序的過程中 從個位開始依次排序 然後十位依次排序 然後百位依次排序
算法過程
1.構造二維數組用來作爲存放排序過程的容器
2.循環操作 從個位開始進行一次比較 將各個數字按照個位大小存入然後按照各個位置的元素依次從小取出,每一個位置上遵循先進先出
代碼實現

public void sort(int[] array) {
        //首先確定排序的趟數;     
        int max = array[0];
        for (int i = 1; i < array.length; i++) {
            if (array[i] > max) {
                max = array[i];
            }
        }
        int time = 0;
        //判斷位數;     
        while (max > 0) {
            max /= 10;
            time++;
        }
        //建立10個隊列;     
        List<ArrayList> queue = new ArrayList<ArrayList>();
        for (int i = 0; i < 10; i++) {
            ArrayList<Integer> queue1 = new ArrayList<Integer>();
            queue.add(queue1);
        }
        //進行time次分配和收集;     
        for (int i = 0; i < time; i++) {
            //分配數組元素;     
            for (int j = 0; j < array.length; j++) {
                //得到數字的第time+1位數;   
                int x = array[j] % (int) Math.pow(10, i + 1) / (int) Math.pow(10, i);
                ArrayList<Integer> queue2 = queue.get(x);
                queue2.add(array[j]);
                queue.set(x, queue2);
            }
            int count = 0;//元素計數器;     
            //收集隊列元素;     
            for (int k = 0; k < 10; k++) {
                while (queue.get(k).size() > 0) {
                    ArrayList<Integer> queue3 = queue.get(k);
                    array[count] = queue3.get(0);
                    queue3.remove(0);
                    count++;
                }
            }
        }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章