手写题目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))
相关推荐
码事漫谈1 分钟前
AI提效,到底能强到什么程度?
前端·后端
IT_陈寒2 分钟前
React hooks依赖数组这个坑差点把我埋了
前端·人工智能·后端
涛声依旧393167 分钟前
Python项目实战:学生信息管理系统
开发语言·python·数据挖掘
阿祖zu29 分钟前
内容创作 AI 透明化声明倡议与项目开源
前端·后端·github
企鹅的蚂蚁31 分钟前
【ESP32-S3开发踩坑】C++野指针引发的LoadProhibited死机与CMake依赖锁死排查
开发语言·c++
XiaoQiao66699934 分钟前
python 简单题目练手【详解版】【1】
开发语言·python
lpfasd12334 分钟前
TypeScript + Cloudflare 全家桶部署项目全流程
前端·javascript·typescript
Kiling_070434 分钟前
Java多态、final与抽象类:面向对象编程进阶指南
java·开发语言
ZC跨境爬虫38 分钟前
极验滑动验证码自动化实战:背景提取、缺口定位与Playwright滑动模拟
前端·爬虫·python·自动化
智算菩萨40 分钟前
【Python图像处理】2 数字图像基础与Python图像表示
开发语言·图像处理·python