zoukankan      html  css  js  c++  java
  • 容易忘记的冒泡排序,选择排序,插入排序,及冒泡排序的优化

    1.普通冒泡排序

    for(let i=0;i<arr.length-1;i++){

                for(let j=0;j<arr.length-1-i;j++){
                    if(arr[j]>arr[j+1]){
                        let t = arr[j]
                        arr[j] = arr[j+1]
                        arr[j+1] = t
                    }
                }
     }
     
    2.选择排序
     
    for(let i=0;i<arr.length;i++){
                let index = i
                for(let j=index+1;j<arr.length;j++){
                    if(arr[j]<arr[index]){
                        index = j
                    }
                    
                }
                if(index === i){
                    continue
                }else{
                    let t = arr[index]
                    arr[index] = arr[i]
                    arr[i] = t
                }
    }
     
    3.插入排序(也是这三种最简单的)
     
    for(let i=0;i<len;i++){
                for(let j=i+1;j>0;j--){
                    if(arr[j]<arr[j-1]){
                        let t = arr[j]
                        arr[j] = arr[j-1]
                        arr[j-1] = t
                    }else{
                        break
                    }
                }
    }
    4.冒泡排序优化
     
    var low = 0;
                var high = arr.length - 1; //设置变量的初始值
                var tmp, j;
                while (low < high) {
                    for (j = low; j < high;++j){
                        if (arr[j] > arr[j + 1]) {
                            tmp = arr[j];
                            arr[j] = arr[j + 1];
                            arr[j + 1] = tmp;
                        }
                    }
                    --high
                    console.log(arr,low,high)
                    for (j = high; j > low;--j){
                        if (arr[j] < arr[j - 1]) {
                            tmp = arr[j];
                            arr[j] = arr[j - 1];
                            arr[j - 1] = tmp;
                        }
                    }
                    ++ low
    }
  • 相关阅读:
    函数和指针
    SQL Server 2005 存储过程
    位数组
    C的名字空间
    C奇特的声明
    位字段
    Git忽略规则
    常用C库简介
    《SQL Server 2005 编程入门经典》第一到十二章
    Linus:利用二级指针删除单向链表
  • 原文地址:https://www.cnblogs.com/MDGE/p/14677164.html
Copyright © 2011-2022 走看看