top of page
Caută
  • Poza scriitoruluioanaunciuleanu

Counting Sort Algorithm in C++



Counting Sort algorithm is used to sort elements of an array, that are placed between a small range. The values can repeat them self. It first counts the number of occurrences of each value, and then calculates the starting index for each value.



// Counting Sort

#include <iostream>
using namespace std;

void countSort(int arrayOfNumbers[], int numberOfElements)
{
  int sortedArray[numberOfElements];
  int countOccurrences[numberOfElements];
  int maxValue = arrayOfNumbers[0];

  // Find the max value
  for (int i = 1; i < numberOfElements; i++)
  {
    if (arrayOfNumbers[i] > maxValue)
      maxValue = arrayOfNumbers[i];
  }

  // Set the array with zeros
  for (int i = 0; i <= maxValue; ++i)
  {
    countOccurrences[i] = 0;
  }

  // Find the number of occurrences
  for (int i = 0; i < numberOfElements; i++)
  {
    countOccurrences[arrayOfNumbers[i]]++;
  }

   // Add the sum of occurrences
  for (int i = 1; i <= maxValue; i++)
  {
    countOccurrences[i] += countOccurrences[i - 1];
  }

  for (int i = numberOfElements - 1; i >= 0; i--)
  {
    sortedArray[countOccurrences[arrayOfNumbers[i]] - 1] = arrayOfNumbers[i];
    countOccurrences[arrayOfNumbers[i]]--;
  }

  // Restore the elements in the original array
  for (int i = 0; i < numberOfElements; i++)
  {
    arrayOfNumbers[i] = sortedArray[i];
  }
}

void printElementsOfArray(int arrayOfNumbers[], int numberOfElements)
{
    for (int i = 0; i < numberOfElements; i++)
    {
        cout << arrayOfNumbers[i] << " ";
    }
    cout << endl;
}

int main()
{
    int arrayOfNumbers[] = {0, 5, 4, 2, 1, 5, 3, 2, 0, 1};
    int numberOfElements = sizeof(arrayOfNumbers) / sizeof(arrayOfNumbers[0]);
    countSort(arrayOfNumbers, numberOfElements);

    cout<<"The sorted array is: \n";
    printElementsOfArray(arrayOfNumbers, numberOfElements);
    return 0;
}

62 afișări0 comentarii

Postări recente

Afișează-le pe toate

Weighted Job Scheduling in JAVA

You receive a list of jobs that have three elements: start time, finish time and profit. You have to schedule the jobs with no overlapping, in order to obtain the maximum profit. Solution: 1. static

Tiling Problem in JAVA

You can use a board that is 2 x n size. The tiles are of size 2 x 1. Count the number of ways to tile the board. Tiles can be placed vertically 2 x 1 or horizontally as 1 x 2. Solution: 1. static

bottom of page