Counting Sort — Perfect when you have psoitive integers to sort
Counting Sort for Unique Integer Values
RUN THE CODE HERE: https://repl.it/@VinitKhandelwal/counting-sort-javascript
function countingUniqueSort(arr)
{
// set 1 for the index which is there in the input array
const count = [];
for (let i=0; i < arr.length; i++) {
count[arr[i]] = 1;
}
// set indices over input array in order
let j = 0;
for (i=0; i<=count.length; i++) {
if (count[i] === 1) {
arr[j] = i;
j++;
}
}
return arr;
}
Counting Sort for possibly duplicate Integer Values
function countingSort(arr)
{
// increase the value at the index which is there in the input array
const count = [];
for (let i=0; i < arr.length; i++) {
if (count[arr[i]] > 0) {
count[arr[i]]++;
} else {
count[arr[i]] = 1;
}
}
// set indices over input array in order
let j = 0;
let k = 0;
for (i=0; i<=count.length; i++) {
k = count[i];
while (k > 0) {
arr[j] = i;
j++;
k--;
}
}
return arr;
}
Test Input
console.log(`Original Array of Unique Elements: ${[3, 2, 5, 4, 8, 7]}`);
console.log(`Sorted Array of Unique Elements: ${countingUniqueSort([3, 2, 5, 4, 8, 7])}`);
console.log(`Original Array Elements: ${[3, 2, 5, 5, 4, 8, 7]}`);
console.log(`Sorted Array Elements: ${countingSort([3, 2, 5, 5, 4, 8, 7])}`);
Output
Original Array of Unique Elements: 3,2,5,4,8,7
Sorted Array of Unique Elements: 2,3,4,5,7,8
Original Array Elements: 3,2,5,5,4,8,7
Sorted Array Elements: 2,3,4,5,5,7,8
Comments
Post a Comment