void CountSort(int* a, int n) { assert(a); int minValue = a[0]; int maxValue = a[0]; for (int i = 0; i < n; ++i) { if (minValue > a[i]) { minValue = a[i]; } if (maxValue < a[i]) { maxValue = a[i]; } } int range = maxValue-minValue+1; int* tmp = new int[range]; memset(tmp, 0, sizeof(int)*range); int index = 0; while (index < n) { tmp[a[index]-minValue]++; ++index; } index = 0; for (int i = 0; i < range; ++i) { while (tmp[i]--) { a[index++] = i+minValue; } } delete[] tmp; }
时间: 2024-10-13 16:26:10