Radix sort will not consider the value of the element, but the value of the digit of the element. For example, when comparing 345, 673, 122, the radix sort first consider the third (last) digits and compare, so the result will be
122
673
345
Then radix sort will compare the second digit, and the result after comparison is
122
345
673
Finally, it will compare the first digit, and the result is
122
345
673
The radix sort will use counting sort to sort the digits in the array, the reason why we use counting sort other than quick sort, merge sort is that counting sort will not disturb the sequence in the original array. For example, if 234 is in front of 235, after sorting the second digit, the order will be 234, 235, it will not be 235, 234.
class RadixSortAlgorithm { public void RadixSort(int[] arrayA, int k) { for (int i = 1; i <= k; i++) { int[] arrayB = new int[arrayA.Length]; //temorary sorted array of arrayA int[] arrayC = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; //count the number of digits for (int j = 0; j < arrayA.Length; j++) { int digit = arrayA[j] / (int)Math.Pow(10, i - 1) - (arrayA[j] / (int)Math.Pow(10, i)) * 10; //get the digit arrayC[digit] += 1; } // this two for loops below is part of the counting sort for (int j = 1; j < arrayC.Length; j++) { arrayC[j] += arrayC[j - 1]; } for (int j = 0; j < arrayA.Length; j++) { int digit = arrayA[j] / (int)Math.Pow(10, i - 1) - (arrayA[j] / (int)Math.Pow(10, i)) * 10; arrayB[arrayC[digit] - 1] = arrayA[j]; arrayC[digit]--; } // pass the sorted array to arrayA for (int j = 0; j < arrayB.Length; j++) { arrayA[j] = arrayB[j]; } } } }
Reference: