Skip to content

feat : added counting sort method #170

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions sorts/counting_sort.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* @author dev-madhurendra
* Counting sort is an algorithm for sorting a collection
* of objects according to keys that are small integers.
* @see https://en.wikipedia.org/wiki/Counting_sort
* @example
* const array = [3, 0, 2, 5, 4, 1]
* countingSort(array, 0, 5)
*/

export const countingSort = (inputArr: number[], min: number, max: number) => {
const sortedArr = []

const count = new Array(max - min + 1).fill(0)

for (let i = 0; i < inputArr.length; i++)
count[inputArr[i] - min]++

count[0] -= 1

for (let i = 1; i < count.length; i++)
count[i] += count[i - 1]

for (let i = inputArr.length - 1; i >= 0; i--) {
sortedArr[count[inputArr[i] - min]] = inputArr[i]
count[inputArr[i] - min]--
}

return sortedArr
}
28 changes: 28 additions & 0 deletions sorts/test/counting_sort.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { countingSort } from "../counting_sort";

const testCases = [
[
[3, 0, 2, 5, 4, 1],
[0, 1, 2, 3, 4, 5],
],
[
[6, 4, 2, 1, 3, 5],
[1, 2, 3, 4, 5, 6],
],
[
[11, 14, 12, 15, 16, 13],
[11, 12, 13, 14, 15, 16],
],
[
[13, 18, 2, 15, 43, 11],
[2, 11, 13, 15, 18, 43],
],
];

it.each(testCases)(
'The countingSort of the array %p is %p',
(input, expected) => {
const res = countingSort(input, Math.min(...input), Math.max(...input));
expect(res).toEqual(expected);
}
);