The Algorithm: Informal

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 2

The algorithm

[edit] Informal
1. Count the discrete elements in the array. (after calculating the minimum and the maximum) 2. Accumulate the counts. 3. Fill the destination array from backwards: put each element to its countth position. Each time put in a new element decrease its count.

[edit] C++ implementation


/// countingSort - sort an array of values. /// /// For best results the range of values to be sorted /// should not be significantly larger than the number of /// elements in the array. /// /// \param A - input - set of values to be sorted /// \param num_of_elements - input - number of elements in the input and output arrays /// \return sorted - new ordered array of the first num_of_elements of the /// input array. caller is responsible for freeing this array. /// int* countingSort(const int A[], const int num_of_elements) { // search for the minimum and maximum values in the input int min = A[0], max = min; for (int i = 1; i < num_of_elements; ++i) { if (A[i] < min) min = A[i]; else if (A[i] > max) max = A[i]; } // create a counting array, counts, with a member for // each possible discrete value in the input. // initialize all counts to 0. int distinct_element_count = max - min + 1; int* counts = new int[distinct_element_count]; // C for (int i = 0; i < distinct_element_count; ++i) counts[i] = 0; // for each value in the unsorted array, increment the // count in the corresponding element of the count array for (int i = 0; i < num_of_elements; ++i) ++counts[ A[i] - min ]; // accumulate the counts - the result is that counts will hold // the offset into the sorted array for the value associated with that index for (int i = 1; i < distinct_element_count; ++i)

counts[i] += counts[ i - 1 ]; // store the elements in a new ordered array int* sorted = new int[num_of_elements]; // B for (int i = num_of_elements - 1; i >= 0; --i) // decrementing the counts value ensures duplicate values in A // are stored at different indices in sorted. sorted[ --counts[ A[i] - min ] ] = A[i]; delete[] counts; return sorted; }

You might also like