-
-
Save conste11ations/61a2bf33ba1fba3c49854b5e88cd9492 to your computer and use it in GitHub Desktop.
Exploring bucket sort in JavaScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// InsertionSort to be used within bucket sort | |
function insertionSort(array) { | |
var length = array.length; | |
for(var i = 1; i < length; i++) { | |
var temp = array[i]; | |
for(var j = i - 1; j >= 0 && array[j] > temp; j--) { | |
array[j+1] = array[j]; | |
} | |
array[j+1] = temp; | |
} | |
return array; | |
} | |
// Implement bucket sort | |
function bucketSort(array, bucketSize) { | |
if (array.length === 0) { | |
return array; | |
} | |
// Declaring vars | |
var i, | |
bucketSize = bucketSize || 200; | |
// Initializing buckets | |
const minValue = Math.min.apply(Math, array); | |
const maxValue = Math.max.apply(Math, array); | |
var bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1; | |
console.log("bucketCount", bucketCount); | |
var allBuckets = new Array(bucketCount); | |
for (i = 0; i < allBuckets.length; i++) { | |
allBuckets[i] = []; | |
} | |
// Pushing values to buckets | |
array.forEach(function (currentVal) { | |
allBuckets[Math.floor((currentVal - minValue) / bucketSize)].push(currentVal); | |
}); | |
// Sorting buckets | |
array.length = 0; | |
allBuckets.forEach(function(bucket) { | |
insertionSort(bucket); | |
bucket.forEach(function (element) { | |
array.push(element) | |
}); | |
}); | |
return array; | |
} | |
var arr1 = [-1, 5, 6, 7, -2]; | |
console.log(bucketSort(arr1, 10)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment