DSA Lab Manual(Counting sort)
DSA Lab Manual(Counting sort)
Objective:
To understand and implement the Counting Sort algorithm using C++ and analyze its working.
Theory:
Counting Sort is a non-comparison-based sorting algorithm that sorts integers by counting the
occurrences of each element. It works efficiently for integers or objects that can be mapped to a
range of integers. The algorithm assumes that the range of the input data is known beforehand.
Advantages:
Time complexity is O(n + k), where n is the number of elements and k is the range of
input values.
Suitable for sorting datasets with small integer ranges.
Disadvantages:
Algorithm:
Program Code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> output(n);
for (int i = n - 1; i >= 0; i--) {
output[--count[arr[i] - min]] = arr[i];
}
int arr[n];
cout << "Enter the elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
countingSort(arr, n);
Sample Input/Output:
Input:
Output:
Sorted array: 2 2 3 3 4 8
Observations:
Viva Questions:
The Counting Sort algorithm is an efficient method for sorting data with a known range. It
avoids comparisons by using frequency counts, making it faster for certain datasets. However, it
is not ideal for datasets with large ranges due to high space requirements.