最近在看后缀数组和后缀树的相关知识,经常提到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。仅供自己学习知识的积累。