排序算法是《數(shù)據(jù)結構與算法》中最基本的算法之一。排序算法可以分為內部排序和外部排序,內部排序是數(shù)據(jù)記錄在內存中進行排序,而外部排序是因排序的數(shù)據(jù)很大,一次不能容納全部的排序記錄,在排序過程中需要訪問外存。常見的內部排序算法有:插入排序、希爾排序、選擇排序、冒泡排序、歸并排序、快速排序、堆排序、基數(shù)排序等。以下是基數(shù)排序算法:
基數(shù)排序是一種非比較型整數(shù)排序算法,其原理是將整數(shù)按位數(shù)切割成不同的數(shù)字,然后按每個位數(shù)分別比較。由于整數(shù)也可以表達字符串(比如名字或日期)和特定格式的浮點數(shù),所以基數(shù)排序也不是只能使用于整數(shù)。
1. 基數(shù)排序 vs 計數(shù)排序 vs 桶排序基數(shù)排序有兩種方法:
這三種排序算法都利用了桶的概念,但對桶的使用方法上有明顯差異:
基數(shù)排序:根據(jù)鍵值的每位數(shù)字來分配桶;計數(shù)排序:每個桶只存儲單一鍵值;桶排序:每個桶存儲一定范圍的數(shù)值;2. LSD 基數(shù)排序動圖演示代碼實現(xiàn)JavaScript實例 //LSD Radix Sortvar counter = [];function radixSort(arr, maxDigit) {? ? var mod = 10;? ? var dev = 1;? ? for (var i = 0; i < maxDigit; i++, dev *= 10, mod *= 10) {? ? ? ? for(var j = 0; j < arr.length; j++) {? ? ? ? ? ? var bucket = parseInt((arr[j] % mod) / dev);? ? ? ? ? ? if(counter[bucket]==null) {? ? ? ? ? ? ? ? counter[bucket] = [];? ? ? ? ? ? }? ? ? ? ? ? counter[bucket].push(arr[j]);? ? ? ? }? ? ? ? var pos = 0;? ? ? ? for(var j = 0; j < counter.length; j++) {? ? ? ? ? ? var value = null;? ? ? ? ? ? if(counter[j]!=null) {? ? ? ? ? ? ? ? while ((value = counter[j].shift()) != null) {? ? ? ? ? ? ? ? ? ? ? arr[pos++] = value;? ? ? ? ? ? ? ? }? ? ? ? ? }? ? ? ? }? ? }? ? return arr;}Java實例 /**?* 基數(shù)排序?* 考慮負數(shù)的情況還可以參考: https://code.i-harness.com/zh-CN/q/e98fa9?*/public class RadixSort implements IArraySort {? ? @Override? ? public int[] sort(int[] sourceArray) throws Exception {? ? ? ? // 對 arr 進行拷貝,不改變參數(shù)內容? ? ? ? int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);? ? ? ? int maxDigit = getMaxDigit(arr);? ? ? ? return radixSort(arr, maxDigit);? ? }? ? /**? ? ?* 獲取最高位數(shù)? ? ?*/? ? private int getMaxDigit(int[] arr) {? ? ? ? int maxValue = getMaxValue(arr);? ? ? ? return getNumLenght(maxValue);? ? }? ? private int getMaxValue(int[] arr) {? ? ? ? int maxValue = arr[0];? ? ? ? for (int value : arr) {? ? ? ? ? ? if (maxValue < value) {? ? ? ? ? ? ? ? maxValue = value;? ? ? ? ? ? }? ? ? ? }? ? ? ? return maxValue;? ? }? ? protected int getNumLenght(long num) {? ? ? ? if (num == 0) {? ? ? ? ? ? return 1;? ? ? ? }? ? ? ? int lenght = 0;? ? ? ? for (long temp = num; temp != 0; temp /= 10) {? ? ? ? ? ? lenght++;? ? ? ? }? ? ? ? return lenght;? ? }? ? private int[] radixSort(int[] arr, int maxDigit) {? ? ? ? int mod = 10;? ? ? ? int dev = 1;? ? ? ? for (int i = 0; i < maxDigit; i++, dev *= 10, mod *= 10) {? ? ? ? ? ? // 考慮負數(shù)的情況,這里擴展一倍隊列數(shù),其中 [0-9]對應負數(shù),[10-19]對應正數(shù) (bucket + 10)? ? ? ? ? ? int[][] counter = new int[mod * 2][0];? ? ? ? ? ? for (int j = 0; j < arr.length; j++) {? ? ? ? ? ? ? ? int bucket = ((arr[j] % mod) / dev) + mod;? ? ? ? ? ? ? ? counter[bucket] = arrayAppend(counter[bucket], arr[j]);? ? ? ? ? ? }? ? ? ? ? ? int pos = 0;? ? ? ? ? ? for (int[] bucket : counter) {? ? ? ? ? ? ? ? for (int value : bucket) {? ? ? ? ? ? ? ? ? ? arr[pos++] = value;? ? ? ? ? ? ? ? }? ? ? ? ? ? }? ? ? ? }? ? ? ? return arr;? ? }? ? /**? ? ?* 自動擴容,并保存數(shù)據(jù)? ? ?*? ? ?* @param arr? ? ?* @param value? ? ?*/? ? private int[] arrayAppend(int[] arr, int value) {? ? ? ? arr = Arrays.copyOf(arr, arr.length + 1);? ? ? ? arr[arr.length - 1] = value;? ? ? ? return arr;? ? }}PHP實例 function radixSort($arr, $maxDigit = null){? ? if ($maxDigit === null) {? ? ? ? $maxDigit = max($arr);? ? }? ? $counter = [];? ? for ($i = 0; $i < $maxDigit; $i++) {? ? ? ? for ($j = 0; $j < count($arr); $j++) {? ? ? ? ? ? preg_match_all('/d/', (string) $arr[$j], $matches);? ? ? ? ? ? $numArr = $matches[0];? ? ? ? ? ? $lenTmp = count($numArr);? ? ? ? ? ? $bucket = array_key_exists($lenTmp - $i - 1, $numArr)? ? ? ? ? ? ? ? ? intval($numArr[$lenTmp - $i - 1])? ? ? ? ? ? ? ? : 0;? ? ? ? ? ? if (!array_key_exists($bucket, $counter)) {? ? ? ? ? ? ? ? $counter[$bucket] = [];? ? ? ? ? ? }? ? ? ? ? ? $counter[$bucket][] = $arr[$j];? ? ? ? }? ? ? ? $pos = 0;? ? ? ? for ($j = 0; $j < count($counter); $j++) {? ? ? ? ? ? $value = null;? ? ? ? ? ? if ($counter[$j] !== null) {? ? ? ? ? ? ? ? while (($value = array_shift($counter[$j])) !== null) {? ? ? ? ? ? ? ? ? ? $arr[$pos++] = $value;? ? ? ? ? ? ? ? }? ? ? ? ? }? ? ? ? }? ? }? ? return $arr;}C++實例 int maxbit(int data[], int n) //輔助函數(shù),求數(shù)據(jù)的最大位數(shù){? ? int maxData = data[0];? ? ? ? ? ? ? ///< 最大數(shù)? ? /// 先求出最大數(shù),再求其位數(shù),這樣有原先依次每個數(shù)判斷其位數(shù),稍微優(yōu)化點。? ? for (int i = 1; i < n; ++i)? ? {? ? ? ? if (maxData < data[i])? ? ? ? ? ? maxData = data[i];? ? }? ? int d = 1;? ? int p = 10;? ? while (maxData >= p)? ? {? ? ? ? //p *= 10; // Maybe overflow? ? ? ? maxData /= 10;? ? ? ? ++d;? ? }? ? return d;/* ? ?int d = 1; //保存最大的位數(shù)? ? int p = 10;? ? for(int i = 0; i < n; ++i)? ? {? ? ? ? while(data[i] >= p)? ? ? ? {? ? ? ? ? ? p *= 10;? ? ? ? ? ? ++d;? ? ? ? }? ? }? ? return d;*/}void radixsort(int data[], int n) //基數(shù)排序{? ? int d = maxbit(data, n);? ? int *tmp = new int[n];? ? int *count = new int[10]; //計數(shù)器? ? int i, j, k;? ? int radix = 1;? ? for(i = 1; i <= d; i++) //進行d次排序? ? {? ? ? ? for(j = 0; j < 10; j++)? ? ? ? ? ? count[j] = 0; //每次分配前清空計數(shù)器? ? ? ? for(j = 0; j < n; j++)? ? ? ? {? ? ? ? ? ? k = (data[j] / radix) % 10; //統(tǒng)計每個桶中的記錄數(shù)? ? ? ? ? ? count[k]++;? ? ? ? }? ? ? ? for(j = 1; j < 10; j++)? ? ? ? ? ? count[j] = count[j - 1] + count[j]; //將tmp中的位置依次分配給每個桶? ? ? ? for(j = n - 1; j >= 0; j--) //將所有桶中記錄依次收集到tmp中? ? ? ? {? ? ? ? ? ? k = (data[j] / radix) % 10;? ? ? ? ? ? tmp[count[k] - 1] = data[j];? ? ? ? ? ? count[k]--;? ? ? ? }? ? ? ? for(j = 0; j < n; j++) //將臨時數(shù)組的內容復制到data中? ? ? ? ? ? data[j] = tmp[j];? ? ? ? radix = radix * 10;? ? }? ? delete []tmp;? ? delete []count;}C實例 #include參考地址:
https://github.com/hustcc/JS-Sorting-Algorithm/blob/master/10.radixSort.md
https://zh.wikipedia.org/wiki/%E5%9F%BA%E6%95%B0%E6%8E%92%E5%BA%8F
以下是熱心網友對基數(shù)排序算法的補充,僅供參考:
熱心網友提供的補充1:
java 代碼里,mod 每次循環(huán)會乘 10,但 counter 的行數(shù)是不需要變的,能包含 [-9,9] 就可以了。
for (int i = 0; i < maxDigit; i++, dev *= 10, mod *= 10) { // 考慮負數(shù)的情況,這里擴展一倍隊列數(shù),其中 [0-9]對應負數(shù),[10-19]對應正數(shù) (bucket + 10) int[][] counter = new int[20][0]; for (int j = 0; j < arr.length; j++) { int bucket = ((arr[j] % mod) / dev) + 10; counter[bucket] = arrayAppend(counter[bucket], arr[j]); } int pos = 0; for (int[] bucket : counter) { for (int value : bucket) { arr[pos++] = value; } } }
熱心網友提供的補充2:
艾孜爾江補充使用C#基數(shù)排序算法如下:
///基數(shù)排序 static void RadixSort(Listlist) { int maxValue = list.Max();//列表內部方法拿過來用用(在Linq中) int it = 0;//需要幾趟 //maxvalue 9-1 99-2 999-3 //10^0<=9 10^1>9 it=1 //10^0<99 10^1<99 10^2>99 it=2 while (Math.Pow(10, it) <= maxValue) { List > buckets = new List
>(10);//分10個桶對應0-9 for (int i = 0; i < 10; i++) { buckets.Add(new List
()); }//列表初始化大小 for (int i = 0; i < list.Count; i++)//入桶 { //989 it=0 989/10^it=989 989%10=9; int digit = (int)((list[i]) / (Math.Pow(10, it)) % 10);//得到對應桶 buckets[digit].Add(list[i]); }//全部入桶 list.Clear();//依次取出來 for (int i = 0; i < buckets.Count; i++) { list.AddRange(buckets[i]); } it += 1;//繼續(xù)下一次循環(huán)入桶出桶 } }
熱心網友提供的補充3:
補充一下python的基數(shù)排序代碼實現(xiàn):
def radix_sort(data): if not data: return [] max_num = max(data) # 獲取當前數(shù)列中最大值 max_digit = len(str(abs(max_num))) # 獲取最大的位數(shù) dev = 1 # 第幾位數(shù),個位數(shù)為1,十位數(shù)為10··· mod = 10 # 求余數(shù)的除法 for i in range(max_digit): radix_queue = [list() for k in range(mod * 2)] # 考慮到負數(shù),我們用兩倍隊列 for j in range(len(data)): radix = int(((data[j] % mod) / dev) + mod) radix_queue[radix].append(data[j]) pos = 0 for queue in radix_queue: for val in queue: data[pos] = val pos += 1 dev *= 10 mod *= 10 return data
熱心網友提供的補充4:
go 的補一個吧:
// 基數(shù)排序 func RadixSort(arr []int) { // 計算最長的數(shù)字 var ( maxVal int maxLen int ) for _, v := range arr { if maxVal < v { maxVal = v } } for maxVal > 0 { maxLen++ maxVal /= 10 } // 循環(huán)進行數(shù)據(jù)分配與回歸 var ( base = 1 // 取余基數(shù),初始是1,用于取出每個元素的倒數(shù)第 i+1 位的值,計算公式:v / base %10 buckets = [10][]int{} // 基數(shù)桶,10個 ) for i := 0; i < maxLen; i++ { // 遍歷位 for _, v := range arr { // 遍歷數(shù)組 d := v / base % 10 // 每個數(shù)字當前位值 buckets[d] = append(buckets[d], v) // 存入對應桶中 } // 將桶中元素還原到arr idx := 0 for x, bucket := range buckets { if len(bucket) == 0 { continue } for _, v := range bucket { arr[idx] = v idx++ } // 桶清空 buckets[x] = []int{} } base *= 10 // 基數(shù)*10 } }
熱心網友提供的補充5:
補上python的實現(xiàn)代碼:
def radixSort(nums): """ 基數(shù)排序,數(shù)組元素必須是正整數(shù) >>>nums = [334, 5, 67, 345, 7, 99, 4, 23, 78, 45, 1, 3453, 23424] >>>radixSort(nums) >>>[1, 4, 5, 7, 23, 45, 67, 78, 99, 334, 345, 3453, 23424] """ #遍歷數(shù)組獲取數(shù)組最大值和最大值對應的位數(shù) maxValue = nums[0] for n in nums: maxValue = max(n, maxValue) #迭代次數(shù) iterCount = len(str(maxValue)) for i in range(iterCount): #定義桶,大小為10,對應0-9 bucket = [[] for _ in range(10)] for n in nums: index = (n//10**i)%10 bucket[index].append(n) #nums數(shù)組清零,并合并桶內元素至nums nums.clear() for b in bucket: nums.extend(b) print(nums) return nums nums = [334, 5, 67, 345, 7, 99, 4, 23, 78, 45, 1, 3453, 23424] radixSort(nums)
熱心網友提供的補充6:
上面 Java 版本有點問題:
for (int i = 0; i < maxDigit; i++, dev *= 10, mod *= 10) { // 考慮負數(shù)的情況,這里擴展一倍隊列數(shù),其中 [0-9]對應負數(shù),[10-19]對應正數(shù) (bucket + 10) int[][] counter = new int[mod * 2][0]; .... }
counter 數(shù)組的定義,會隨著 mod 不斷乘 10 變得越來越大。理論上 counter 數(shù)組只需要容量為 20 就可以表示負數(shù)與正數(shù)的所有數(shù)字字符。
另外,方法 getMaxDigit 計算數(shù)字的最大長度,只考慮到最大值的長度,沒有考慮當存在負數(shù)時,最小值負數(shù)的字符長度也可能是最大的長度。
更新后的版本:
/** 基數(shù)排序 */ public class RadixSort { public int[] sort(int[] arr) { int maxDigit = getMaxDigit(arr); return radixSort(arr, maxDigit); } /** * 獲取最高位數(shù) */ private int getMaxDigit(int[] arr) { int maxValue = getMaxValue(arr); int minValue = getMinValue(arr); return Math.max(getNumLength(maxValue), getNumLength(minValue)); } private int getMaxValue(int[] arr) { int maxValue = arr[0]; for (int value : arr) { if (maxValue < value) { maxValue = value; } } return maxValue; } private int getMinValue(int[] arr) { int minValue = arr[0]; for (int value : arr) { if (minValue > value) { minValue = value; } } return minValue; } protected int getNumLength(long num) { if (num == 0) { return 1; } int lenght = 0; for (long temp = num; temp != 0; temp /= 10) { lenght++; } return lenght; } private int[] radixSort(int[] arr, int maxDigit) { int mod = 10; int dev = 1; for (int i = 0; i < maxDigit; i++, dev *= 10, mod *= 10) { // 考慮負數(shù)的情況,這里擴展一倍隊列數(shù),其中 [0-9]對應負數(shù),[10-19]對應正數(shù) (bucket + 10) int[][] counter = new int[20][0]; for (int j = 0; j < arr.length; j++) { int bucket = ((arr[j] % mod) / dev) + 10; counter[bucket] = arrayAppend(counter[bucket], arr[j]); } int pos = 0; for (int[] bucket : counter) { for (int value : bucket) { arr[pos++] = value; } } } return arr; } /** * 自動擴容,并保存數(shù)據(jù) * * @param arr * @param value */ private int[] arrayAppend(int[] arr, int value) { arr = Arrays.copyOf(arr, arr.length + 1); arr[arr.length - 1] = value; return arr; } }以上為基數(shù)排序算法詳細介紹,插入排序、希爾排序、選擇排序、冒泡排序、歸并排序、快速排序、堆排序、基數(shù)排序等排序算法各有優(yōu)缺點,用一張圖概括:
關于時間復雜度
平方階 (O(n2)) 排序 各類簡單排序:直接插入、直接選擇和冒泡排序。
線性對數(shù)階 (O(nlog2n)) 排序 快速排序、堆排序和歸并排序;
O(n1+§)) 排序,§ 是介于 0 和 1 之間的常數(shù)。 希爾排序
線性階 (O(n)) 排序 基數(shù)排序,此外還有桶、箱排序。
關于穩(wěn)定性
穩(wěn)定的排序算法:冒泡排序、插入排序、歸并排序和基數(shù)排序。
不是穩(wěn)定的排序算法:選擇排序、快速排序、希爾排序、堆排序。
名詞解釋:
n:數(shù)據(jù)規(guī)模
k:"桶"的個數(shù)
In-place:占用常數(shù)內存,不占用額外內存
Out-place:占用額外內存
穩(wěn)定性:排序后 2 個相等鍵值的順序和排序之前它們的順序相同