复杂度为O(n)的排序方法

特殊情况下,排序其实可以做到O(n)的复杂度哦,请看如下例题和说明,这种排序的应用十分广泛,而且速度快,缺点就是需要用空间来换时间

1
/* 2 问题描述:如何对公司所有员工的年龄进行排序呢?公司有几万名员工,要求时间复杂度为O(n) 3 解题思路:总体思路是“用时间换空间”这样的问题一般有这样的特点 4 1、数字有一定的范围,如本次的年龄,范围假设为0-99 5 2、数字一定要为整数,因为一个数组的元素是另一个数组的下标 6 3、允许的空间复杂度为O(n); 7 这种排序方法叫“bucket sort” 8 */ 9 10 void SortAges(int ages[], int length) 11 { 12 if (ages == nullptr || length <= 0) 13 return; 14 const int theOldestAge = 99; 15 int timesOfAges[theOldestAge + 1] = { 0 }; 16 for (int i = 0; i < length; i++) 17 { 18 if (ages[i] >= 0 && ages[i] <= 99) 19 timesOfAges[ages[i]]++; 20 else 21 throw new std::exception("out og range"); 22 } 23 int index = 0; //技术变量可以不参与循环体,妙哉 24 for (int i = 0; i <= theOldestAge; i++) 25 { 26 for (int j = 0; j < timesOfAges[i]; j++) 27 { 28 ages[index] = i; 29 index++; 30 } 31 } 32 } 33 int main(int argc, char* argv[]) 34 { 35 const int numOfWorkers = 1000; 36 int ageOfWorkers[numOfWorkers]; 37 srand((unsigned)time(NULL)); 38 for (int i = 0; i < numOfWorkers; i++) 39 ageOfWorkers[i] = rand() % 100; 40 cout << "ages:" << endl; 41 for (int i = 0; i < numOfWorkers; i++) 42 { 43 cout << ageOfWorkers[i] << " "; 44 if ((i + 1) % 5 == 0) 45 cout << endl; 46 } 47 SortAges(ageOfWorkers, numOfWorkers); 48 cout << "sorted ages:" << endl; 49 for (int i = 0; i < numOfWorkers; i++) 50 { 51 cout << ageOfWorkers[i] << " "; 52 if ((i + 1) % 5 == 0) 53 cout << endl; 54 } 55 system("pause"); 56 return 0; 57 }
原文地址:https://www.cnblogs.com/dapeng-bupt/p/7128232.html