ALGORITHM:Sort-CountingSort
Posted xinyueliu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ALGORITHM:Sort-CountingSort相关的知识,希望对你有一定的参考价值。
#include "stdafx.h" #include <iostream> static void print(int arrayOld[], int n) { for (int i = 0; i < n; i++) { if (i == n - 1) { std::cout << arrayOld[i] << std::endl; } else { std::cout << arrayOld[i] << ","; } } } static int getMax(int a[], int n) { int max = a[0]; for (int i = 0; i < n; i++) { if (a[i] > max) { max = a[i]; } } return max; } static int getMin(int a[], int n) { int min = a[0]; for (int i = 0; i < n; i++) { if (a[i] < min) { min = a[i]; } } return min; } static void countingSort(int a[], int n, int unused[]) { int min = getMin(a, n) , max = getMax(a, n) , idxLen = max - min + 1 , *idxFlg = new int[idxLen] ; memset(idxFlg, 0, sizeof(int) * idxLen); for (int i = 0; i < n; i++) { idxFlg[a[i] - min]++; } for (int i = 1; i < idxLen; i++) { idxFlg[i] += idxFlg[i - 1]; } for (int i = n - 1; i >= 0; i--) { unused[idxFlg[a[i] - min] - 1] = a[i]; } } int _tmain(int argc, _TCHAR* argv[]) { int array[10] = {18, 7,29, 2, 105, 4, 1, 61, 0, 3000}; int dst[10] = {0}; int n = sizeof(array) / sizeof(array[0]); print(array, n); countingSort(array, n, dst); print(dst, n); getchar(); }
以上是关于ALGORITHM:Sort-CountingSort的主要内容,如果未能解决你的问题,请参考以下文章