zoukankan      html  css  js  c++  java
  • js中sort()方法冒泡排序模拟

    1.sort()方法概述

      sort() 方法用于对数组的元素进行排序。

      如果调用该方法时没有使用参数,将按字母顺序对数组中的元素进行排序,说得更精确点,是按照字符编码的顺序进行排序。要实现这一点,

      首先应把数组的元素都转换成字符串(如有必要),以便进行比较。

      如果想按照其他标准进行排序,就需要提供比较函数,该函数要比较两个值,然后返回一个用于说明这两个值的相对顺序的数字。

      比较函数应该具有两个参数 a 和 b,其返回值如下:

       若 a 小于 b,在排序后的数组中 a 应该出现在 b 之前,则返回一个小于 0 的值。

       若 a 等于 b,则返回 0。

       若 a 大于 b,则返回一个大于 0 的值。

     1 Array.prototype.bubbleSort = function(fun){
     2     for(var i = 0; i < this.length - 1; i++){//趟数
     3         var flag = true;
     4         for(var j = 0; j < this.length - i - 1 ; j++){//每趟比较之后会得出一个最大值沉底
     5             if(typeof fun == "function"){
     6                 if(fun(this[j], this[j+1])>0){
     7                     //交换
     8                     flag = false;
     9                     var temp;
    10                     temp = this[j];
    11                     this[j] = this[j+1];
    12                     this[j+1] = temp;
    13                 }
    14             }else{
    15                 if(this[j] > this[j+1]){
    16                     //交换
    17                     flag = false;
    18                     var temp;
    19                     temp = this[j];
    20                     this[j] = this[j+1];
    21                     this[j+1] = temp;
    22                 }
    23             }
    24         }
    25         if(flag == true){
    26             break;
    27         }
    28     }
    29     return this;
    30 }
    31 var arr3 = arr.bubbleSort(function(a,b){
    32     return b-a;
    33 });
    34 console.log(arr3);
  • 相关阅读:
    【Linux】- 文件基本属性
    【Linux】- mv命令
    【Linux】- 守护进程supervisor安装使用
    【Linux】- rm命令
    【Linux】- 开启远程连接
    【Redis】- 安装为windows服务
    Apache2.4 与 php7.1.6的链接
    apache2.4 的安装
    MySQL v5.7.18 版本解压安装
    网站系统消息表设计
  • 原文地址:https://www.cnblogs.com/guangyan/p/6685100.html
Copyright © 2011-2022 走看看