基數排序(C#)
代碼實現:
/// <summary><br /> /// 基數排序<br /> /// </summary><br /> /// <param name="arrayToSort">要排序的數組</param><br /> /// <param name="maxDigit">數位最大位元</param><br /> /// <returns>排序後的結果</returns><br /> public static int[] RadixSort(int[] arrayToSort, int maxDigit)<br /> {<br /> for (int i = 0; i < maxDigit; i++)<br /> {<br /> int[] tempArray = new int[arrayToSort.Length];<br /> int[] countingArray = new int[10];<br /> // 初始化計數數組<br /> for (int j = 0; j < 10; j++)<br /> {<br /> countingArray[j] = 0;<br /> }</p><p> // 元素計數<br /> for (int j = 0; j < arrayToSort.Length; j++)<br /> {<br /> int splitNum = (int)(arrayToSort[j] / Math.Pow(10, i)) - (int)(arrayToSort[j] / Math.Pow(10, i + 1)) * 10;<br /> countingArray[splitNum] = countingArray[splitNum] + 1;<br /> }<br /> // 計數小與等於某元素的個數<br /> for (int j = 1; j < 10; j++)<br /> {<br /> countingArray[j] += countingArray[j - 1];<br /> }</p><p> for (int j = arrayToSort.Length - 1; j >= 0; j--)<br /> {<br /> int splitNum = (int)(arrayToSort[j] / Math.Pow(10, i)) - (int)(arrayToSort[j] / Math.Pow(10, i + 1)) * 10;<br /> int splitNumIndex = countingArray[splitNum] - 1;<br /> tempArray[splitNumIndex] = arrayToSort[j];</p><p> countingArray[splitNum] -= 1;<br /> }</p><p> Array.Copy(tempArray, arrayToSort, tempArray.Length);<br /> }</p><p> return arrayToSort;<br /> }