C++ Program to Implement Sorting of Less than 100 Numbers in O(n) Complexity


To sort some small numbers in linear time we can use the counting sort technique.

Counting sort is a stable sorting technique, which is used to sort objects according the keys that are small numbers. It counts the number of keys whose key values are same. This sorting technique is efficient when difference between different keys are not so big, otherwise it can increase the space complexity.

The complexity of counting Sort Technique

  • Time Complexity: O(n + r)

  • Space Complexity: O(n + r)

Input − A list of unsorted data: 2 5 6 2 3 10 3 6 7 8
Output − Array after Sorting: 2 2 3 3 5 6 6 7 8 10

Algorithm

countingSort(array, size)

Input − An array of data, and the total number in the array

Output − The sorted Array

Begin
   max = get maximum element from array.
   define count array of size [max+1]
   for i := 0 to max do
      count[i] = 0 //set all elements in the count array to 0
   done
   for i := 1 to size do
      increase count of each number which have found in the array
   done
   for i := 1 to max do
      count[i] = count[i] + count[i + 1] //find cumulative frequency
   done
   for i := size to 1 decrease by 1 do
      store the number in the output array
      decrease count[i]
   done
   return the output array
End

Example Code 

#include <iostream>
using namespace std;
void counting_sort(int array[], int n) {
   int i, j;
   int count[n];
   for (i = 0; i < n; i++)
      count[i] = 0;
   for (i = 0; i < n; i++)
      (count[array[i]])++;
   for (i = 0, j = 0; i < n; i++)
      for (; count[i] > 0; (count[i])--)
         array[j++] = i;
}
int main() {
   int array[100], i, num;
   cout << "Enter the size of array : ";
   cin >> num;
   cout << "Enter the " << num << " elements to be sorted:" << endl;
   for (i = 0; i < num; i++)
      cin >> array[i];
   cout << "\nThe array of elements before sorting : " <<endl;
   for (i = 0; i < num; i++)
      cout << array[i] << " ";
   cout << "\nThe array of elements after sorting : " << endl;
   counting_sort(array, num);
   for (i = 0; i < num; i++)
      cout << array[i] << " ";
   return 0;
}

Output

Enter the size of array : 8

Enter the 8 elements to be sorted:
54 89 23 20 18 88 65 31

The array of elements before sorting :
54 89 23 20 18 88 65 31

The array of elements after sorting :
54 89 23 20 18 88 65 31

Updated on: 30-Jul-2019

231 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements