排序 (5)计数排序“概念”
1. 應(yīng)用場景
一是需要排序的元素必須是整數(shù),二是排序元素的取值要在一定范圍內(nèi),并且比較集中。
1.1 思想
step1. 統(tǒng)計數(shù)組中每個值為 X 的元素出現(xiàn)的次數(shù),存入數(shù)組 C 的第X 項
step2. 累加元素出現(xiàn)次數(shù)(計算不超過 X包括X 的元素的個數(shù))
step3. 反向填充目標數(shù)組:將元素X依次逐個放入到適當?shù)奈恢?/p>
void countSort(int arr[], int len) { //1.獲得數(shù)列的最大值int max = arr[0];for (int i = 1; i < len; i++) {if (arr[i] > max)max = arr[i];}//2.根據(jù)數(shù)列的最大值肯定統(tǒng)計數(shù)組的長度int* countArray = new int[max + 1]{};//3.遍歷數(shù)列,填充統(tǒng)計數(shù)組for (int i = 0; i < len; i++)countArray[arr[i]]++;//4.遍歷統(tǒng)計數(shù)組,輸出結(jié)果int index = 0; for (int i = 0; i < max + 1; i++) {while (countArray[i] > 0) { arr[index++] = i;countArray[i]--;}} }
1.2 min優(yōu)化
空間不一定需要max那么多個。計算max-min個即可。
void countSort(int arr[], int len) {//1.獲得數(shù)列的最大值和最小值int max = arr[0];for (int i = 1; i < len; i++) {if (arr[i] > max)max = arr[i];} int min = arr[0];for (int i = 1; i < len; i++) {if (arr[i] < min)min = arr[i];}//2.初始化計數(shù)數(shù)組count的長度int* countArray = new int[max - min + 1]{};//3.遍歷數(shù)列,填充統(tǒng)計數(shù)組for (int i = 0; i < len; i++)countArray[arr[i] - min]++;// A中的元素要減去最小值,再作為新索引//4.遍歷統(tǒng)計數(shù)組,輸出結(jié)果int index = 0;for (int i = 0; i < max + 1; i++) {while (countArray[i] > 0) {arr[index++] = i + min;countArray[i]--;}}}【引用】
[1] 代碼countSort.h
總結(jié)
以上是生活随笔為你收集整理的排序 (5)计数排序“概念”的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: kth (1)概述
- 下一篇: 排序 (2)快速排序-多个数组