手写题目4:快速获取数组中最大的三项

快速获取数组中最大的三项

Start

转换那么多本质上还是排序,这里快速编写常见的排序算法

1. sort

js 复制代码
var arr = [123, 3, 12, 14, 2, 45, 1, 5, 7, 2, 10]
var result = arr.sort((a, b) => { return a - b })

console.log(result.slice(-3))

2. 冒泡

js 复制代码
var arr = [123, 3, 12, 14, 2, 45, 1, 5, 7, 2, 10]


function bolo(array) {

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

    for (let j = 0; j < array.length - i - 1; j++) {
      if (array[j] > array[j + 1]) {
        let temp = array[j]
        array[j] = array[j + 1]
        array[j + 1] = temp
      }
    }

  }

  return array
}

console.log(bolo(arr).slice(-3))

3. 快排

js 复制代码
var arr = [123, 3, 12, 14, 2, 45, 1, 5, 7, 2, 10]

function quickSort(array) {
  if (array.length <= 1) {
    return array
  }
  var left = []
  var right = []
  var centerIndex = Math.floor(array.length / 2)
  var centerElement = array.splice(centerIndex, 1)[0]

  for (let index = 0; index < array.length; index++) {
    const element = array[index];
    if (element < centerElement) {
      left.push(element)
    } else {
      right.push(element)
    }
  }

  return quickSort(left).concat([centerElement], quickSort(right))

}

console.log(quickSort(arr))
相关推荐
python零基础入门小白8 分钟前
【万字长文】大模型应用开发:意图路由与查询重写设计模式(从入门到精通)
java·开发语言·设计模式·语言模型·架构·大模型应用开发·大模型学习
天若有情67316 分钟前
【c++】手撸C++ Promise:从零实现通用异步回调组件,支持链式调用+异常安全
开发语言·前端·javascript·c++·promise
无心水16 分钟前
【Python实战进阶】1、Python高手养成指南:四阶段突破法从入门到架构师
开发语言·python·django·matplotlib·gil·python实战进阶·python工程化实战进阶
抱琴_35 分钟前
【Vue3】大屏性能优化黑科技:Vue 3 中实现请求合并,让你的大屏飞起来!
前端·vue.js
不会玩电脑的Xin.36 分钟前
HTML + CSS
前端·css·html
q***31831 小时前
Windows安装Rust环境(详细教程)
开发语言·windows·rust
hadage2331 小时前
--- JavaScript 的一些常用语法总结 ---
java·前端·javascript
彭于晏爱编程1 小时前
🍭🍭🍭升级 AntD 6:做第一个吃螃蟹的人
前端
合作小小程序员小小店1 小时前
桌面安全开发,桌面二进制%恶意行为拦截查杀%系统安全开发3.0,基于c/c++语言,mfc,win32,ring3,dll,hook,inject,无数据库
c语言·开发语言·c++·安全·系统安全