手写题目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))
相关推荐
北冥you鱼几秒前
Go语言常用包使用指南:从标准库到第三方利器
开发语言·microsoft·golang
石像鬼₧魂石8 分钟前
【Y2Ksoft】贵阳陈桥饭店ERP管理系统
大数据·前端·物联网·html·数据库架构
俺不中嘞9 分钟前
python常用函数
开发语言·python
TheITSea14 分钟前
4、React+Tailwind CSS
前端·css·react.js
weedsfly22 分钟前
前端开发中的代理模式——从 Vue 3 响应式到日常开发
前端·javascript·面试
Li.map36 分钟前
CesiumJS 地图主题系统:用着色器打造实时滤镜
javascript·arcgis·cesium·着色器
用户2986985301439 分钟前
在 React 中通过 JavaScript 实现 Excel 单元格、行与列的锁定保护
javascript·react.js·excel
এ慕ོ冬℘゜42 分钟前
深入理解 JavaScript 事件对象:从 target 到 preventDefault 的实战指南
开发语言·前端·javascript
学逆向的1 小时前
汇编——修改EIP的值
开发语言·汇编·网络安全
weixin_422329311 小时前
AgentScope Java ReActAgent 核心循环深度解析
java·开发语言·人工智能