#include <iostream>
using namespace std;
/*
高考满分是750分,某省有n个考生,如何用尽可能低的时间复杂度来对所有考生的分数进行排序
时间复杂度o(n)
*/
void countSort(int a[], int n, int k)
{
int *countArr = new int[k + 1];
int *finalArr = new int[n];
int i = 0;
for (i = 0; i <= k; i++)
{
countArr[i]=0;
}
for(i = 0; i < n; i++)
{
cout << (countArr[a[i]]++) << endl;
//countArr[a[i]]++;
}
for(i = 1; i <= k; i++)
{
countArr[i] += countArr[i -1];
cout << countArr[i] << " " << countArr[i - 1]<< endl;
}
for(i = 0; i < n; i++)
{
finalArr[--countArr[a[i]]] = a[i];
cout << finalArr[countArr[a[i]]] <<endl;
}
for(i= 0 ; i < n; i ++)
{
a[i]= finalArr[i];
}
delete [] finalArr;
delete [] countArr;
}
int main()
{
int a[] = {2, 1, 2, 3, 0};
int n = sizeof(a) / sizeof(a[0]);
int maxPossibleScore = 3;
countSort(a, n, maxPossibleScore);
int i = 0;
for(i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
return 0;
}
计数排序
最新推荐文章于 2024-10-18 22:43:15 发布