Skip to content
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

Create Pigeonhole.js #417

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
37 changes: 37 additions & 0 deletions Coding/JavaScript/Pigeonhole.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Pigeonhole Sort Algorithm in JavaScript
// GitHub: https://github.com/uppy19d0

function pigeonholeSort(arr) {
let min = arr[0];
let max = arr[0];

for (let i = 1; i < arr.length; i++) {
if (arr[i] < min) {
min = arr[i];
}
if (arr[i] > max) {
max = arr[i];
}
}

const range = max - min + 1;
const holes = new Array(range).fill().map(() => []);

for (let i = 0; i < arr.length; i++) {
holes[arr[i] - min].push(arr[i]);
}

let index = 0;
for (let i = 0; i < range; i++) {
for (const value of holes[i]) {
arr[index++] = value;
}
}

return arr;
}

// Example usage:
const inputArray = [8, 3, 2, 7, 4, 6, 8];
const sortedArray = pigeonholeSort(inputArray);
console.log("Sorted order is:", sortedArray);