Reputation: 308
How the elements of an array got sorted by using counting sort two times??
Is it fixed that there would be the use of counting sort exact two times?
I know it is related to radix sort (which is the subroutine of counting sort) in which elements are sorted by considering each digit at a time.
for more detail:- https://www.geeksforgeeks.org/sort-n-numbers-range-0-n2-1-linear-time/
(please don't declare it as a duplicate I have already checked posts related to this.)
How will the elements be of two-digit after converting the numbers to base n? Can you tell me this, please?
Thanks in advance.
Upvotes: 0
Views: 2726
Reputation: 58320
The trick described in the article is to consider the elements of the array as 2-digit numbers in base n, and them sort them using two passes of counting sort.
The idea is that sorting the numbers by the bottom digit (using a stable sorting algorithm), and then sorting the numbers by the higher digit (using the same stable sorting algorithm) results in the numbers being sorted. These two steps can be considered a form of radix sort except rather than sorting by bit, it's sorting by digits base n.
Given that the digits are all in the range 0..n-1, it's possible to use counting sort to do each of the two sorting steps in linear time. There's some fiddly details to get right so that the counting sort is stable, but those details (and code) are provided in the article.
Upvotes: 2