手写题目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))
相关推荐
咖啡の猫41 分钟前
搭建Python开发环境
开发语言·python
程序猿小蒜2 小时前
基于springboot的共享汽车管理系统开发与设计
java·开发语言·spring boot·后端·spring·汽车
lsp程序员0102 小时前
使用 Web Workers 提升前端性能:让 JavaScript 不再阻塞 UI
java·前端·javascript·ui
J***Q2923 小时前
前端路由,React Router
前端·react.js·前端框架
1***81533 小时前
前端路由参数传递,React与Vue实现
前端·vue.js·react.js
听风吟丶3 小时前
Java 8 Stream API 高级实战:从数据处理到性能优化的深度解析
开发语言·python
hygge9993 小时前
Spring Boot + MyBatis 整合与 MyBatis 原理全解析
java·开发语言·经验分享·spring boot·后端·mybatis
q***13613 小时前
十七:Spring Boot依赖 (2)-- spring-boot-starter-web 依赖详解
前端·spring boot·后端
xixixi777774 小时前
了解一下Sentry(一个开源的实时错误监控平台)
前端·安全·开源·安全威胁分析·监控·sentry