Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using a hash table valid in counting sort (in place of an array)?

The classic counting sort example requires you to build an array of size equal to the greatest integer of your input array.

For example, if your array is [1, 6, 3, 10000, 8] you would need an array 10000 long for the counting sort.

Could this not be done in the same linear time using a hash table on the integers? Just a simple map?

In python, it'd be something like:

counting_map = {n: 0 for n in input_array}  # start by mapping all to 0
for num in input_array:
    counting_map[n] += 1

I know this really only works well for integers, but in that case is the mapping solution not superior?

Time-complexity wise, you initialize the map in O(n) time, then iterate through the array in O(n) time, then perform hashing functions on input in O(1) time. (Obviously big-O notation isn't the final determining factor of whether an algorithm is good, I just want to make sure I have the theory correct here).

Is this a good solution, or does the "original" counting sort still do something superior that I don't see? I'm also curious why a "hashmap-based counting sort" hardly returns any Google search results, making it seem like it's hardly ever used. Is the overhead of the hashing enough to outweigh its smaller memory footprint?

like image 350
bob Avatar asked Sep 01 '15 23:09

bob


People also ask

Can we sort an array using hashing?

You can use the sort method on an array, hash, or another Enumerable object & you'll get the default sorting behavior (sort based on <=> operator)

Is counting sort hashing?

Counting sort is a sorting algorithm that sorts the elements with the technique of counting the number of occurrences of each unique element in an array or list. Counting algorithm is basically a hashing technique with the keys between a specific range and then counting the number of objects having distinct key values.

What are the limitations of counting sort algorithm?

Counting sort only works when the range of potential items in the input is known ahead of time. Space cost. If the range of potential values is big, then counting sort requires a lot of space (perhaps more than O ( n ) O(n) O(n)).

Is counting sort in place?

Is counting sort an in-place sorting algorithm? Answer: No, counting sort is not an in-place sorting algorithm. In in-place sorting algorithms, only a small/constant auxiliary space is used; in counting sort, we use an auxiliary array of the size of the range of data.


1 Answers

You can do that, and the construction would be O(n) with the obvious memory benefit.

With one little problem.

To output the sorted array, you'll still need to sort the hash table keys. And that problem is exactly what you were trying to solve in the first place.

like image 132
Juan Lopes Avatar answered Nov 05 '22 18:11

Juan Lopes