計數排序《演算法很美》
阿新 • • 發佈:2020-12-20
計數排序
計數排序:優點:快
缺點:資料範圍大,比較稀疏,會導致輔助空間很大,也稀疏,造成空間的浪費
計數排序:
- 一句話:用輔助陣列對陣列中出現的數字計數,元素轉下標,下標轉元素
- 假設元素均大於等於0,依次掃描原陣列,將元素值k記錄在輔助陣列的k位上
- 依次掃描輔助陣列,如果為1,將其插入目標陣列的空白處
- 問題
- 重複元素
- 有負數
我的思路: 先利用Util.maxOf
開闢一個最大的輔助空間。然後讓輔助空間根據source的數進行++,然後遍歷helper[],將helper[i]>0的值轉到source['current++]中,同時helper[i]–消除可能重複的例子
具體思路:
-
int[] helper = new int[Util.maxOf(source) + 1];
開闢輔助陣列 -
將輔助陣列根據source[]的值進行++for(int e : source){
helper[e]++;
} -
for (int i = 1; i < helper.length; i++)
遍歷helper[i] -
如果helper[i]有>0,則將helper[i]的值放入source[current++]=i中,同時也要helper[i]–,
package onetwo;
public class 計數排序 {
public static void sort(int[] source){
int[] helper = new int[Util.maxOf(source) + 1];
for(int e : source){
helper[e]++;
}
int current = 0; //資料回填的位置
for (int i = 1; i < helper.length; i++){
while (helper[i]>0){
//下標轉元素
source[ current++] = i;
//可能會有重複的例子所以--
helper[i]--;
}
}
}
public static void main(String[] args){
int[] arr = {1,5,3,6,2,68,3,4};
sort(arr);
Util.print(arr);
}
public static int maxOf(int[] source) {
int nmax = source[0];
int num=source.length;
for(int i=0;i<num;i++)
{
if(source[i]>=nmax)
nmax=source[i];
}
return nmax;
}
}