手写题目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))
相关推荐
weixin_425023007 分钟前
PG JSONB 对应 Java 字段 + MyBatis-Plus 完整实战
java·开发语言·mybatis
weixin_4434785121 分钟前
Flutter第三方常用组件包之路由管理
前端·javascript·flutter
武藤一雄25 分钟前
C# 异步回调与等待机制
前端·microsoft·设计模式·微软·c#·.netcore
啥都不懂的小小白32 分钟前
前端CSS入门详解
前端·css
leaves falling38 分钟前
C++ string 类:从入门到模拟实现
开发语言·c++
智算菩萨41 分钟前
【Tkinter】15 样式与主题深度解析:ttk 主题系统、Style 对象与跨平台样式管理实战
开发语言·python·ui·ai编程·tkinter
子非鱼@Itfuture1 小时前
`<T> T execute(...)` 泛型方法 VS `TaskExecutor<T>` 泛型接口对比分析
java·开发语言
weixin_419349791 小时前
Python 项目中生成 requirements.txt 文件
开发语言·python
林恒smileZAZ1 小时前
前端大屏适配方案:rem、vw/vh、scale 到底选哪个?
开发语言·前端·css·css3
QQ5110082851 小时前
基于区块链的个人医疗咨询挂号信息系统vue
前端·vue.js·区块链