lsd_radix_sort.h
#ifndef _LSDRADIX_SORT_H_
#define _LSDRADIX_SORT_H_
using namespace std;
class Record
{
public:
Record();
Record(int x,int y=0);
int the_key()const;
int key;
int other;
};
bool operator>(const Record &x,const Record &y);
bool operator<(const Record &x,const Record &y);
bool operator==(const Record &x,const Record &y);
bool operator%(const Record &x,const int &y);
bool operator/(const Record &x,const int &y);
ostream &operator<<(ostream &output,Record &x);
Record::Record()
{
key=0;
other=0;
}
Record::Record(int x,int y)
{
key=x;
other=y;
}
int Record::the_key()const
{
return key;
}
bool operator>(const Record &x,const Record &y)
{
return x.the_key()>y.the_key();
}
bool operator<(const Record &x,const Record &y)
{
return x.the_key()<y.the_key();
}
bool operator==(const Record &x,const Record &y)
{
return x.the_key()==y.the_key();
}
bool operator%(const Record &x,const int &y)
{
return x.the_key()%y;
}
bool operator/(const Record &x,const int &y)
{
return x.the_key()/y;
}
ostream &operator<<(ostream &output,Record &x)
{
output<<x.the_key();
output<<endl;
}
#endif // _LSDRADIX_SORT_H_
main.cpp
#include <iostream>
#include "lsdradix_sort.h"
using namespace std;
void lsdradix_sort(Record arr[],int begin,int end,int d);
int getdigit(Record a,int b);
int main()
{
Record a[10];
a[0]=Record(35,18);
a[1]=Record(5,1);
a[2]=Record(16,8);
a[3]=Record(98,10);
a[4]=Record(95,188);
a[5]=Record(47,108);
a[6]=Record(32,118);
a[7]=Record(36,128);
a[8]=Record(48,128);
a[9]=Record(10,138);
/*for(int i=0;i<10;i++)
{
cout<<a[i];
}*/
lsdradix_sort(a,0,9,2);
for(int i=0;i<10;i++)
{
cout<<a[i];
}
return 0;
}
void lsdradix_sort(Record arr[],int begin,int end,int d) {
const int radix = 10;
int count[radix]={0}, i, j;
//所有桶的空间开辟
Record *bucket = (Record*)malloc((end-begin+1)*sizeof(Record));
for(int k=1;k<=d;k++)
{
//从低位到高位依次进行排序
//统计各桶需要装的元素的个数
for(i = begin; i <= end; ++i)
{
count[getdigit(arr[i],k)]++;
}
/*******这里d=1, 计算后
count[0]=1, count[5]=2
count[1]=0, count[6]=3
count[2]=1, count[7]=1
count[3]=0, count[8]=2
count[4]=0, count[9]=0
********/
//求出桶的边界索引,count[i]值为第i个桶的右边界索引+1
for(i = 1; i < radix; ++i)
{
count[i] = count[i] + count[i-1];
}
/*******
这里计算每个桶在bucket里的边界,count[i-1]至count[i]-1为其边界
count[0]=1, count[5]=4
count[1]=1, count[6]=7
count[2]=2, count[7]=8
count[3]=2, count[8]=10
count[4]=2, count[9]=10
********/
for(i=end;i>=begin;i--)
{
j = getdigit(arr[i], k);
//求出关键码的第k位的数字
bucket[count[j]-1] = arr[i];
//放入对应的桶中,count[j]-1是第j个桶的右边界索引
--count[j]; //对应桶的装入数据索引减一
}
//从各个桶中收集数据
for(i = begin,j=begin; i <= end; ++i, ++j)
{ arr[i] = bucket[j];
//cout<<arr[i];
}
//这时arr中的内容变为: [10,32,95,36,16,36,47,98,48]
for(i=begin;i<=end;i++)
{
count[i]=0;
}
}
}
int getdigit(Record a,int b)
{
int temp;
if(b==1)
{
temp=a.key%10;
}
if(b==2)
{
temp=a.key/10;
}
//cout<<temp<<endl;
return temp;
}