|
| 1 | + |
| 2 | +var HpcAlgorithms = HpcAlgorithms || {}; |
| 3 | + |
| 4 | +HpcAlgorithms.Sorting = (function() |
| 5 | +{ |
| 6 | + var HistogramOneByteComponentUInt8 = function(inArray) |
| 7 | + { |
| 8 | + var numberOfBins = 256; |
| 9 | + |
| 10 | + var count = new Array(numberOfBins); |
| 11 | + for (var b = 0; b < numberOfBins; b++) |
| 12 | + count[b] = 0; |
| 13 | + |
| 14 | + for (var i = 0; i < inArray.length; i++) |
| 15 | + count[ inArray[i] ]++; |
| 16 | + |
| 17 | + return count; |
| 18 | + } |
| 19 | + |
| 20 | + /** |
| 21 | + * Counting Sort of typed unsigned byte array |
| 22 | + * This algorithm is in-place |
| 23 | + * @param {Array of bytes} inputArray Array of numbers, which must be a typed array of unsigned bytes |
| 24 | + * @return {Array of bytes} Sorted array of unsigned bytes |
| 25 | + */ |
| 26 | + var SortCountingUInt8 = function(inputArray) |
| 27 | + { |
| 28 | + var count = HistogramOneByteComponentUInt8(inputArray); |
| 29 | + |
| 30 | + var startIndex = 0; |
| 31 | + for (var countIndex = 0; countIndex < count.length; countIndex++) |
| 32 | + { |
| 33 | + inputArray.fill(countIndex, startIndex, startIndex + count[countIndex]); // 2X faster than using a for loop to fill an array |
| 34 | + startIndex += count[countIndex]; |
| 35 | + } |
| 36 | + return inputArray; |
| 37 | + } |
| 38 | + |
| 39 | + var HistogramOneWordComponent = function(inArray) |
| 40 | + { |
| 41 | + var numberOfBins = 65536; |
| 42 | + |
| 43 | + var count = new Array(numberOfBins); |
| 44 | + for (var b = 0; b < numberOfBins; b++) |
| 45 | + count[b] = 0; |
| 46 | + |
| 47 | + for (var current = 0; current < inArray.length; current++) |
| 48 | + count[ inArray[current] ]++; |
| 49 | + |
| 50 | + return count; |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * Counting Sort of typed unsigned short array typed array |
| 55 | + * This algorithm is in-place |
| 56 | + * @param {Array of unsigned short} inputArray Array of numbers, which must be a typed array of unsigned short |
| 57 | + * @return {Array of unsigned short} Sorted array of unsigned short numbers |
| 58 | + */ |
| 59 | + var SortCountingUInt16 = function(inputArray) |
| 60 | + { |
| 61 | + var count = HistogramOneWordComponent(inputArray); |
| 62 | + |
| 63 | + var startIndex = 0; |
| 64 | + for (var countIndex = 0; countIndex < count.length; countIndex++) |
| 65 | + { |
| 66 | + inputArray.fill(countIndex, startIndex, startIndex + count[countIndex]); |
| 67 | + startIndex += count[countIndex]; |
| 68 | + } |
| 69 | + return inputArray; |
| 70 | + } |
| 71 | + |
| 72 | + return { |
| 73 | + SortCountingUInt8: SortCountingUInt8, |
| 74 | + SortCountingUInt16: SortCountingUInt16 |
| 75 | + }; |
| 76 | +})(); |
0 commit comments