Sorting without comparison of elements

Given an array with integer elements in small range, sort the array. We need to write a non-comparison based sorting algorithm with following assumptions about input.

  1. All the entries in the array are integers.
  2. The difference between the maximum value and the minimum value in the array is less than or equal to 10^6.
Input : arr[] = {10, 30, 20, 4}
Output : 4 10 20 30

Input : arr[] = {10, 30, 1, 20, 4}
Output : 1 4 10 20 30


We are not allowed to use comparison based sorting algorithms like QuickSort, MergeSort, etc.

Since elements are small, we use array elements as index. We store element counts in a count array. Once we have count array, we traverse the count array and print every present element its count times.

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to sort an array without comparison
// operator.
#include <bits/stdc++.h>
using namespace std;
  
int sortArr(int arr[], int n, int min, int max)
{
    // Count of elements in given range 
    int m = max - min + 1;
      
    // Count frequencies of all elements
    vector<int> c(m, 0);
    for (int i=0; i<n; i++)
       c[arr[i] - min]++;
  
    // Traverse through range. For every
    // element, print it its count times.
    for (int i=0; i<=m; i++)
        for  (int j=0; j < c[i]; j++)
          cout << (i + min) << " ";
}
  
int main()
{
    int arr[] =  {10, 10, 1, 4, 4, 100, 0};
    int min = 0, max = 100;
    int n = sizeof(arr)/sizeof(arr[0]);
    sortArr(arr, n, min, max);
    return 0;
}

chevron_right


Output:

0 1 4 4 10 10 100

What is time complexity?
Time complexity of above algorithm is O(n + (max-min))

Is above algorithm stable?
The above implementation is not stable as we do not care about order of sane elements while sorting.

How to make above algorithm stable?
The stable version of above algorithm is called Counting Sort. In counting sort, we store sums of all smaller or equal values in c[i] so that c[i] store actual position of i in sorted array. After filling c[], we traverse input array again, place every element at its position and decrement count.

What are non-comparison based standard algorithms?
Counting Sort, Radix Sort and Bucket Sort.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.