Counting Sort

Counting Sort :-
In computer sciencecounting sort is an algorithm for sorting a collection of objects according to keys that are small integers; that is, it is an integer sorting algorithm. It operates by counting the number of objects that have each distinct key value, and using arithmetic 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 and minimum key values, so it is only suitable for direct use in situations where the variation in keys is not significantly greater than the number of items. However, it is often used as a subroutine in another sorting algorithm, radix sort, that can handle larger keys more efficiently.
Because counting sort uses key values as indexes into an array, it is not a comparison sort,

#include "stdafx.h"  // header file for MS VS
#include <conio.h> // header file
#include <iostream> // some compiler used <iostream.h>
 
using namespace std ;


int main()
{
int a[10] = {9,6,4,2,3,5,7,1,4,8} ;

int a2[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
for (int i = 0; i < 10; i++)
a2[a[i]] += 1;

int index = 0 ;
for (int i = 0; i < 10; i++)
{
for(int j = 0; j < a2[i]; j++)
{
a[index] = i;
index += 1 ;
}
}
for (int i = 0 ; i <= 9 ; i++)
cout << a[i] << " " ;
_getch() ;  // Some compiler uses getch()
return 0 ;
}
Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment