Counting Sort optimization

Open
#498 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
30/100
Issue type
Refactor
Clarity
Needs clarification
Activity status
Stale
Tech stack
javascript
Domain
data

Research direction

Start by locating the Counting Sort implementation and comparing it with the linked TypeScript example. Before changing it, establish whether the proposed one-pass lookup optimization preserves sorting behavior and define tests or measurements that demonstrate correctness and the claimed memory and performance improvement.

Written by the indexing model from the issue text.

Description

Hi devs!
On the very beginning I want to appreciate your work here, I think it is fantastic and gives a lot of addition to developers knowledge!

But this ticket I want to open to point potential optimization of Counting Sort algorithm.

In the implementation there are is loop by all array elements to find smallest and biggest.
Next step is creating counting array of size dependent on smallest and biggest.
And in next step there is one more iteration by all elements to set up counting array.

I am wondering if there could be optimization applied and make all of those in just 1 iteration, moreover there could be used lookup instead of array.

Lets consider this example of array to be sorted:
const arrayToSort = [1, 1, 10000, 1, 1, 10000, 10000, 1, 1];
When switched to lookup object instead of array we will have small object:
{"1": 6, "10000": 3}
When using array it will be bigger:
[0, 6, 0, 0, 0, 0, ....(a lot of zeros), 10000]

So finally we could find biggest, smallest and set lookup values in 1 iteration and having lesser memory used.

I prepared example of that:
*The next difference is that I am preparing algorithm which is mutating original array, but it can be applied here too:
example

Please reply if this make sense to you, I would be more than happy to make MR to your great work!

Dominant language
JavaScript
Stars
197k
Forks
31k
PR merge metrics
No merged PRs in 30d

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from trekhleb/javascript-algorithms

All issues in trekhleb/javascript-algorithms

Similar issues

More JavaScript issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.