计数排序
假设一个数组arr[0...n] 找到最大的值max 然后新建一个数组book[0...max]={1}
遍历数组arr,arr[i]=j book[j]++
最后遍历数组book[0...max] b[i]=b[i-1]+b[i]
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<iostream> #include<stdlib.h> #include<cstring> using namespace std; int main() { int n; cin >> n; int *a = new int[n]; int *c = new int[n]; memset(a, 0, n*sizeof(int)); memset(c, 0, (n+1)*sizeof(int)); int max = 0; for (int i = 0; i < n; i++) { cin >> a[i];//a记录元素 max = a[i]>max ? a[i] : max; } int *b = new int[max+1]; memset(b, 0, (max+1)*sizeof(int)); for (int i = 0; i < n; i++) { b[a[i]]++;//代表当前数字的排名 } for (int i = 1; i < max + 1; i++) { b[i] = b[i] + b[i - 1]; } for (int i = 0; i < n; i++) { b[a[i]]--; c[b[a[i]]] = a[i]; } for (int i = 0; i < n; i++) cout << c[i] << endl; delete[]a; delete[]b; delete[]c; return 0; }
基数排序
相当于多次进行基数排序,它是将各位上的数字进行排序,个位 百位 千位 ,,,,
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
int getDigit(int i, int d) //d的值为1、2、3...,表示要求取的相应位的值,1表示求取个位, { //2表示十分位,类推 int val; while (d--) { val = i % 10; i /= 10; } return val; } //基数排序算法的具体实现 void RadixSort(int *list, int begin, int end, int digit) { int radix = 10; //基数 进制 int i = 0, j = 0; int * count = new int[radix]; //存放各个桶的数据存放个数 int * bucket = new int[end - begin + 1]; for (int d = 1; d <= digit; d++) { for ( i = 0; i < radix; i++) count[i] = 0; //置空各个桶的统计数据 for (i = begin; i <= end; i++) { j = getDigit(list[i], d); count[j]++; } for (i = 1; i < radix; i++) count[i] = count[i] + count[i - 1]; //count[i]表示第i个桶的右边界索引 //将数据依次装入桶中,保证数据的稳定性,此步即为基数排序的分配 for (i = end; i >= begin; i--) { j = getDigit(list[i], d); bucket[count[j] - 1] = list[i]; count[j]--; } //基数排序的收集 //把桶中的数据再倒出来 for (i = begin, j = 0; i <= end; i++, j++) list[i] = bucket[j]; } }