• JavasScript基数排序


    基数排序
     

    91, 46, 85, 15, 92, 35, 31, 22
    经过基数排序第一次扫描之后, 数字被分配到如下盒子中:
    Bin 0:
    Bin 1: 91, 31
    Bin 2: 92, 22
    Bin 3:
    Bin 4:
    Bin 5: 85, 15, 35
    Bin 6: 46
    Bin 7:
    Bin 8:
    Bin 9:

    根据盒子的顺序, 对数字进行第一次排序的结果如下:
    91, 31, 92, 22, 85, 15, 35, 46
    然后根据十位上的数值再将上次排序的结果分配到不同的盒子中:
    Bin 0:
    Bin 1: 15
    Bin 2: 22
    Bin 3: 31, 35
    Bin 4: 46
    Bin 5:
    Bin 6:
    Bin 7:
    Bin 8: 85
    Bin 9: 91, 92
    最后, 将盒子中的数字取出, 组成一个新的列表, 该列表即为排好序的数字:
    62 | 第 5
    15, 22, 31, 35, 46, 85, 91, 92

     使用队列代表盒子, 可以实现这个算法。 我们需要九个队列, 每个对应一个数字。 将所有

    队列保存在一个数组中, 使用取余和除法操作决定个位和十位。 算法的剩余部分将数字加
    入相应的队列, 根据个位数值对其重新排序, 然后再根据十位上的数值进行排序, 结果即
    为排好序的数字。

    function Queue() {
    this.dataStore = [];
    this.enqueue = enqueue;
    this.dequeue = dequeue;
    this.front = front;
    this.back = back;
    this.toString = toString;
    this.empty = empty;
    function enqueue(element) {
    this.dataStore.push(element);
    function dequeue() {
    return this.dataStore.shift();
    function front() {
    return this.dataStore[0];
    function back() {
    return this.dataStore[this.dataStore.length-1];
    }
    function toString() {
    var retStr = ""; 
    for (var i = 0; i < this.dataStore.length; ++i) {
    retStr += this.dataStore[i] + " ";
    return retStr;
    function empty() {
    if (this.dataStore.length == 0) {
    return true;
    }
    else {
    return false;
    }
    }
    function distribute(nums, queues, n, digit) {
    for (var i = 0; i < n; ++i) {
    if (digit == 1) {
    queues[nums[i]%10].enqueue(nums[i]);
    } else {
    queues[Math.floor(nums[i] / 10)].enqueue(nums[i]);
    }
    }
    }
    function dispArray(arr) {
    for (var i = 0; i < arr.length; ++i) {
    console.log(arr[i] + " ");
    }
    }
    function collect(queues, nums) {
    var i = 0;
    for (var digit = 0; digit < 10; ++digit) {
    while (!queues[digit].empty()) {
    nums[i++] = queues[digit].dequeue();
    }
    }
    var queues = [];
    for (var i = 0; i < 10; ++i) {
    queues[i] = new Queue();
    var nums = [];
    for (var i = 0; i < 10; ++i) {
    nums[i] = Math.floor(Math.floor(Math.random() * 101));
    }
    console.log("Before radix sort: ");
    dispArray(nums);
    distribute(nums, queues, 10, 1);
    console.log("收集数据");
    collect(queues, nums);
    distribute(nums, queues, 10, 10);
    collect(queues, nums);
    console.log(" After radix sort: ");
    dispArray(nums);
  • 相关阅读:
    一次有教益的程序崩溃调试 (中)
    读书:手工测试与自动测试
    迭代还是交付?
    用Windbg调试.NET程序的资源泄漏
    一次有教益的程序崩溃调试 (上)
    基于云计算的软件测试服务
    Vcastr 3.0 api
    学习Linux三(Linux常用命令及技巧)
    学习Linux六(Linux必学60个命令之【文件处理】)
    学习Linux四(Linux必学60个命令)
  • 原文地址:https://www.cnblogs.com/wfpanskxin/p/4923415.html
Copyright © 2020-2023  润新知