之前提到的線性時間排序——計數排序,針對於排序數範圍跨度較小,額外消耗的空間不大,而對於序列
{56165,313,255,1354,78}甚至更大的數來說,消耗的空間過大。
這時就用到了基數排序,基數排序可以看作計數排序的擴展
//基數排序
//計數排序作爲一種線性時間排序算法,當排序數的範圍過大,消耗空間也隨之變大。
//基數排序可以看作計數排序的一種擴展,將較大的數按基數,縱向使用計數排序
// Author's E-mail : [email protected] Feel free to contact me for comments on my work
#include<iostream>
using namespace std;
//輸出數組函數
void printArray(int *a,int len){
for (int i = 0; i < len;i++){
cout << a[i] << " ";
}
cout << endl;
}
int* CountSort(int *a, int len,int rad){
int c[10];
int *b = new int[len]; //動態申請數組內存
for (int i = 0; i < 10;i++){
c[i] = 0;
}
int t = 0;
for (int i = 0; i < len;i++){
c[(a[i] / rad)%10]++;
if((a[i] / rad)%10==0){
t++;
}
}
if(t==len){
printArray(a, len);
return NULL;//排序結束
}
for (int i = 1; i < 10;i++){
c[i] += c[i - 1];
}
for (int i = len-1; i >=0;i--){ //這裏必須要用倒敘,原因在於當前位若相同,則倒敘可以不影響之前較小位排序結果
int pos = c[(a[i] / rad) % 10] - 1;
b[c[(a[i] / rad)%10] - 1] = a[i];
c[(a[i] / rad)%10]--;
}
return b;
}
void RadixSort(int *a,int len){
int rad = 1;
while(1){
a = CountSort(a, len, rad);
if(a==NULL){
return;
}else{
rad = rad * 10;
}
}
}
int main(){
int array[5] = {56165, 313, 255, 1354, 78};
RadixSort(array, 5);
system("pause");
return 0;
}