zoukankan      html  css  js  c++  java
  • 分析并封装排序算法(js,java)

    前言

      本次来分享一下排序的api底层的逻辑,这次用js模拟,java的逻辑也是差不多。

      先看封装好的api例子:

      js的sort排序

      java的compareTo排序

     

    自己模拟的代码(JS)

    function compareTo(a,b){
      return a-b;//a-b为从下到大 b-a为从大到小
    }
    
    Object.prototype.newSort = function(Func){
      const flag = Func(1,0);
      const $this = this;
      // 注意:上面for循环的$this.length-1是因为这里只需要走到倒数第二个位置即可,而下面的for循环$this.length-1是数组下标对应的最后一个值
      for(let i = 0; i < $this.length-1; i++){
        for(let j = $this.length-1; j > i; j--){
          // 思路就是从数组第一个开始与倒数第一个向上直到数组第二个的过程中一直比较,如果有比第一个小的,就交换,然后第二次循环就只需要第二个与倒数第二个开始比较,以此类推
          const compare = flag > 0 ? $this[i] > $this[j] : $this[i] < $this[j];
          if(compare){//满足条件就进行位运算来交换位置
            $this[i] = $this[i] ^ $this[j];
            $this[j] = $this[i] ^ $this[j];
            $this[i] = $this[i] ^ $this[j];
          }
        }
      }
    }
    
    var array = [2,1,5,7,3,4,9,8,6,4,5,2,1];
    console.log(array.newSort(compareTo));//[ 1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 7, 8, 9 ]

    源代码

      js源代码

      

      java源代码

  • 相关阅读:
    冲刺第一天(补发)
    进度条05
    npm start问题
    Spring Boot 默认配置无法访问静态资源
    Spring Boot 返回Html界面
    阿里云配置tomcat后不能访问问题
    Spring Boot Web开发中Thymeleaf模板引擎的使用
    tomcat官网改版后下载方式
    Ubuntu16.04进入无限登录状态的解决办法
    Ubuntu16.04安装MySql5.7
  • 原文地址:https://www.cnblogs.com/zxd66666/p/13194458.html
Copyright © 2011-2022 走看看