Radix sort

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:

http://www.cnblogs.com/sun/archive/2008/06/26/1230095.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值