From 8b8575d0584d89d062139aa34c81d4693397b574 Mon Sep 17 00:00:00 2001 From: Panzki Date: Fri, 29 Sep 2017 22:44:01 +0200 Subject: [PATCH 1/2] Added radixsort algorithm. --- Sorts/radixSort.js | 53 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Sorts/radixSort.js diff --git a/Sorts/radixSort.js b/Sorts/radixSort.js new file mode 100644 index 000000000..49b36b80f --- /dev/null +++ b/Sorts/radixSort.js @@ -0,0 +1,53 @@ +/* +* Radix sorts an integer array without comparing the integers. +* It groups the integers by their digits which share the same +* significant position. +* For more information see: https://en.wikipedia.org/wiki/Radix_sort +*/ +function radixSort(items, RADIX) { + + //default radix is then because we usually count to base 10 + if (RADIX === undefined || RADIX < 1) { + RADIX = 10; + } + + var maxLength = false; + var placement = 1; + + while (!maxLength) { + maxLength = true; + var buckets = []; + + for (var i = 0; i < RADIX; i++) { + buckets.push([]); + } + + for (var j = 0; j < items.length; j++) { + var tmp = items[j] / placement; + buckets[Math.round(tmp % RADIX)].push(j); + if (maxLength && tmp > 0) { + maxLength = false; + } + } + + var a = 0; + for (var b = 0; b < RADIX; b++) { + var buck = buckets[b]; + for (var k = 0; k < buck.length; k++) { + items[a] = k; + a++; + } + } + placement *= RADIX; + } + return items; +} + +//Implementation of radixSort + +var ar = [5, 6, 7, 8, 1, 2, 12, 14]; +//Array before Sort +console.log(ar); +radixSort(ar); +//Array after sort +console.log(ar); From a7a192ad0819bc4901f5421268ae5bff896a251b Mon Sep 17 00:00:00 2001 From: Panzki Date: Tue, 10 Oct 2017 12:30:58 +0200 Subject: [PATCH 2/2] Fixed a bug in the radix sort algorithm, that would sort the indexes of the passed array instead of the actual array items. --- Sorts/radixSort.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Sorts/radixSort.js b/Sorts/radixSort.js index 49b36b80f..bb0fca99f 100644 --- a/Sorts/radixSort.js +++ b/Sorts/radixSort.js @@ -24,7 +24,7 @@ function radixSort(items, RADIX) { for (var j = 0; j < items.length; j++) { var tmp = items[j] / placement; - buckets[Math.round(tmp % RADIX)].push(j); + buckets[Math.floor(tmp % RADIX)].push(items[j]); if (maxLength && tmp > 0) { maxLength = false; } @@ -34,7 +34,7 @@ function radixSort(items, RADIX) { for (var b = 0; b < RADIX; b++) { var buck = buckets[b]; for (var k = 0; k < buck.length; k++) { - items[a] = k; + items[a] = buck[k]; a++; } }