手写题目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))
相关推荐
闲猫几秒前
go orm GORM
开发语言·后端·golang
晴空万里藏片云1 小时前
elment Table多级表头固定列后,合计行错位显示问题解决
前端·javascript·vue.js
曦月合一1 小时前
html中iframe标签 隐藏滚动条
前端·html·iframe
奶球不是球1 小时前
el-button按钮的loading状态设置
前端·javascript
kidding7231 小时前
前端VUE3的面试题
前端·typescript·compositionapi·fragment·teleport·suspense
李白同学2 小时前
【C语言】结构体内存对齐问题
c语言·开发语言
无责任此方_修行中3 小时前
每周见闻分享:杂谈AI取代程序员
javascript·资讯
黑子哥呢?3 小时前
安装Bash completion解决tab不能补全问题
开发语言·bash
青龙小码农3 小时前
yum报错:bash: /usr/bin/yum: /usr/bin/python: 坏的解释器:没有那个文件或目录
开发语言·python·bash·liunx
大数据追光猿3 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法