Home >Web Front-end >JS Tutorial >Detailed explanation of radix sorting in JavaScript

Detailed explanation of radix sorting in JavaScript

韦小宝
韦小宝Original
2018-03-14 14:33:032319browse

This article talks about radix sorting in JavaScript. If you don’t know about radix sorting in JavaScript or are interested in radix sorting in JavaScript, then let’s take a look at this article. Okay Let’s stop talking nonsense and get to the point

There are two methods of radix sorting

1. MSD sorts from the high order

2. LSD sorts from the lowest order

Radix sorting vs. counting sort vs. bucket sort


These three sorting algorithms all use the concept of buckets. But there are obvious differences in the use of buckets:

Radix sort: Allocate buckets according to each digit of the key value

Counting sort : Each bucket only stores a single key value

Bucket sorting: Each bucket stores a certain range of values

LSD radix sorting animation demonstration:

Detailed explanation of radix sorting in JavaScript

Radix sorting JavaScript code implementation:

//LSD Radix Sort  
var counter = [];function radixSort(arr, maxDigit) {  
    var mod = 10;  
    var dev = 1;  
    for (var i = 0; i < maxDigit; i++, dev *= 10, mod *= 10) {  
        for(var j = 0; j < arr.length; j++) {  
            var bucket = parseInt((arr[j] % mod) / dev);  
            if(counter[bucket]==null) {  
                counter[bucket] = [];  
            }  
            counter[bucket].push(arr[j]);  
        }  
        var pos = 0;  
        for(var j = 0; j < counter.length; j++) {  
            var value = null;  
            if(counter[j]!=null) {  
                while ((value = counter[j].shift()) != null) {  
                      arr[pos++] = value;  
                }  
          }  
        }  
    }  
    return arr;}

The above is all the content of this article. If you don’t know much about it, you can implement both sides yourself and it will be easy to master. oh!

Related recommendations:

Examples of counting sorting and radix sorting algorithms implemented in JS

The above is the detailed content of Detailed explanation of radix sorting in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn