From 1b4122cfef9765d7b8e3e7916b01b83f3959aad8 Mon Sep 17 00:00:00 2001 From: ngutierrez31 Date: Tue, 19 Feb 2019 21:49:13 -0500 Subject: [PATCH] Updated index.md: C++ implementation for count sort (#26609) * Update index.md Added a C++ implementation to count sort using std::vector * fix: added code block syntax --- .../sorting-algorithms/counting-sort/index.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/guide/english/algorithms/sorting-algorithms/counting-sort/index.md b/guide/english/algorithms/sorting-algorithms/counting-sort/index.md index 8b4cbeda1d..693a8f909c 100644 --- a/guide/english/algorithms/sorting-algorithms/counting-sort/index.md +++ b/guide/english/algorithms/sorting-algorithms/counting-sort/index.md @@ -53,4 +53,21 @@ for (i=0; i < numbers.length; i++) { } ``` +### C++ Implementation +```cpp +#include +void countSort(int upperBound, int lowerBound, std::vector numbersToSort) //lower and upper bounds of numbers in vector +{ + int range = upperBound - lowerBound; //create a range large enough to get every number between the min and max + std::vector counts (range); //initialize of counts of the size of the range + std::fill(counts.begin(), counts.end(), 0); //fill vector of zeros + + for (int i = 0; i < numbersToSort.size(); i++) + { + int index = numbersToSort[i] - lowerBound; //For example, if 5 is the lower bound and numbersToSort[i] is 5. index will be 0 and the counts[index]+= 1; //count of 5 will be stored in counts[0] + } + + std::cout << counts << std::endl; +} +```