开博后第一个程序:radix sort

    最近在看后缀数组和后缀树的相关知识,经常提到radix sort这种排序方法。在google上搜索了一下,radix sort排序方法主要分为两种:LSD(least significant digit)和MSD(most significant digit)。其中LSD是从低位向高位的逐步排序,MSD则是从高位向低位逐步排序。具体的例子可以自己找一下:下面是我参考网页上的相关算法自己实现的radix sort 方法对一个数组的排序,采用的是计数的方法。具体代码如下:

#include <iostream>
#include <cmath>
#include <vector>
using namespace std;

static vector<int> RadixSort(vector<int> &ArrayToSort,int digit)
{
 //low to high digit
 for(int k = 1; k <= digit; k++)
 {
  //temp array to store the sort result inside digit
  vector<int> tmpArray(ArrayToSort.size());
  
  //temp array for countingsort
  vector<int> tmpCountingSortArray(10,0);
  
  //countingsort
  for(unsigned int i = 0; i < ArrayToSort.size(); i++)
  {
   //split the specified digit from the element
   int tmpSplitDigit = ArrayToSort[i]/(int)pow((double)10,(double)(k-1)) - (ArrayToSort[i]/(int)pow((double)10,(double)k))*10;
   tmpCountingSortArray[tmpSplitDigit] += 1;
  }

  for(int m = 1; m < 10;m++)
  {
   tmpCountingSortArray[m] += tmpCountingSortArray[m-1];
  }

  //output the value to result
  for(int i = ArrayToSort.size() - 1; i >= 0; i--)
  {
   int tmpSplitDigit = ArrayToSort[i]/(int)pow((double)10,(double)(k - 1)) - (ArrayToSort[i]/(int)pow((double)10,(double)k)) * 10;
   tmpArray[tmpCountingSortArray[tmpSplitDigit] - 1] = ArrayToSort[i];
   tmpCountingSortArray[tmpSplitDigit] -= 1;
  }
  //copy the digit-inside result to source array
  for(unsigned int p = 0; p < ArrayToSort.size(); p++)
  {
   ArrayToSort[p] = tmpArray[p];
  }
  cout<<"after digit = : "<<k<<" the ArrayToSort is as follows: "<<endl;
  for(unsigned int p = 0; p < ArrayToSort.size(); p++)
   cout<<ArrayToSort[p]<<"/t";
  cout<<endl;
  cout<<endl;
 }
 return ArrayToSort;
}
int main()
{
 int a[] = {332,653,632,755,433,722,48};
 vector<int> ary(a,a+7);
 vector<int> res = RadixSort(ary,3);
 cout<<"terminate: "<<endl;
 vector<int>::iterator  it = res.begin();
 while(it != res.end())
 {
  cout<<*it<<" ";
  it++;
 }
 system("pause");
}

参考的网页是: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、付费专栏及课程。

余额充值