Fastest Sorting Algorithm

Revision en2, by akattack, 2019-10-27 15:27:18

There are many sorting algorithms like merge sort, quick sort, etc to sort a linear data structure.

Of all the sort algorithms the fastest is the Counting sort, whose time complexity is approx O(n).

But counting sort is only viable when

  • values of element lie in the small range.
  • the values are non-negative.

Implementation of Counting Sort in C++

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    int arr[] = {5, 9, 11, 10, 15, 12, 2, 8 ,10};
    countingSort(arr,0,8,2,15);
 
    return 0;
}
 
void countingSort(int arr[], int s, int e, int mn, int mx){
    int i,k=0,sizeTemp = mx-mn+1;
    int temp[sizeTemp]; // Initializing all element of temp array with 0
 
    for(i=0; i<sizeTemp; i++){
        temp[i] = 0;
    }
 
    for(i=0; i<=e; i++){
        temp[arr[i]-mn]++;
    }
 
    for (i=mn; i<=mx; i++){
        while(temp[i-mn]-->0){
            arr[k++]=i;
 
        }
    }
 
    for(i=0; i<=8; i++){
        printf("%d ",arr[i]);
    }
 
}

Output

2 5 8 9 10 10 11 12 15

Reference: My Blog

Tags #sorting, #counting sort, #algorithms, #c++

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en7 English akattack 2019-10-27 16:46:54 97
en6 English akattack 2019-10-27 16:33:52 145
en5 English akattack 2019-10-27 16:22:46 27
en4 English akattack 2019-10-27 16:21:08 11
en3 English akattack 2019-10-27 16:12:22 848
en2 English akattack 2019-10-27 15:27:18 0 (published)
en1 English akattack 2019-10-27 15:26:34 1346 Initial revision (saved to drafts)