zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    PyCharm配置 Git 教程
    Docker实践:基于python:3.7.1-stretch制作python镜像
    Docker开启远程安全访问
    Centos7安装apt-get
    Kubernetes 系列(二):在 Linux 部署多节点 Kubernetes 集群与 KubeSphere 容器平台
    微信小程序调试mock 数据,提示合法域名校验失败
    babel-plugin-import 配置多个组件按需加载时
    docker run -p 8070:80 -d nginx
    数据库的设计(E-R图,数据库模型图,三大范式)
    数据库 范式
  • 原文地址:https://www.cnblogs.com/wfpanskxin/p/4923415.html
Copyright © 2011-2022 走看看