Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Practical – 3

Objective :
To understand Counting sort implement it

Introduction -
Counting sort is an algorithm for sorting a collection of objects according to keys that are small
positive integers; that is, it is an integer sorting algorithm. It operates by counting the number of
objects that possess distinct key values, and applying prefix sum on those counts to determine the
positions of each key value in the output sequence. Its running time is linear in the number of
items and the difference between the maximum key value and the minimum key value, so it is
only suitable for direct use in situations where the variation in keys is not significantly greater
than the number of items. It is often used as a subroutine in radix sort, another sorting algorithm,
which can handle larger keys more efficiently.

Example -
Given array :- 5,7,5,2,1,1
Sorted array :- 1,12,5,5,7

Algorithm -
Step 1: Declare an auxiliary array Aux[] of size max(Arr[])+1 and initialize it with 0.
Step 2: Traverse array Arr[] and map each element of Arr[] as an index of Aux[] array, i.e.,
execute Aux[Arr[i]]++ for 0 <= i < N.
Step 3: Calculate the prefix sum at every index of array Arr[].
Step 4: Create an array sortedArr[] of size N.

Step 5: Traverse array Arr[] from right to left and update sortedArr[] as

sortedArr[ Aux[ Arr[i] ] - 1] - Arr[i]. Also, update Aux[] as Aux[ Arr[i] ].

Code -

#include <stdio.h>
void countingSort(int arr[], int n) {
int arr1[10];
int x = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > x)
x = arr[i];
}
int count_arr[10];
for (int i = 0; i <= x; ++i) {
count_arr[i] = 0;
}
for (int i = 0; i < n; i++) {
count_arr[arr[i]]++;
}
for (int i = 1; i <= x; i++) {
count_arr[i] += count_arr[i - 1];
}
for (int i = n - 1; i >= 0; i--) {
arr1[count_arr[arr[i]] - 1] = arr[i];
count_arr[arr[i]]--;
}
for (int i = 0; i < n; i++) {
arr[i] = arr1[i];
}
}
void display(int arr[], int n) {
for (int i = 0; i < n; ++i) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {4, 2, 2, 8, 3, 3, 1};
int n = sizeof(arr) / sizeof(arr[0]);
countingSort(arr, n);
display(arr, n);
}

OUTPUT –

You might also like