zoukankan      html  css  js  c++  java
  • 前端排序算法

    快速排序的思路:

    1、选择数组中间数作为基数,并从数组中取出此基数;

    2、准备两个数组容器,遍历数组,逐个与基数比对,较小的放左边容器,较大的放右边容器;

    3、递归处理两个容器的元素,并将处理后的数据与基数按大小合并成一个数组,返回。
     
    代码实现:
    let  arr = [85, 24, 63, 45, 17, 31, 96, 50]
    function quickSort (arr) {
        if (arr.length <= 1) { return arr; }
      var pivotIndex= Math.floor(arr.length / 2)
      var pivot = arr.splice(pivotIndex, 1)[0];
      var left = [];
      var right = [];
      for (let index = 0; index < arr.length; index++) {
           if (arr[index]< pivot) {
               left.push(arr[index])
           } else {
               right.push(arr[index])
           }
      }
      return quickSort(left).concat([pivot], quickSort(right))
    
    }
    console.log(quickSort (arr))

    选择数组中间数作为基数,并从数组中取出此基数;

      var pivotIndex= Math.floor(arr.length / 2)
      var pivot = arr.splice(pivotIndex, 1)[0];

    准备两个数组容器,遍历数组,逐个与基数比对,较小的放左边容器,较大的放右边容器

      var left = [];
      var right = [];
      for (let index = 0; index < arr.length; index++) {
           if (arr[index]< pivot) {
               left.push(arr[index])
           } else {
               right.push(arr[index])
           }
      }

    递归处理两个容器的元素,并将处理后的数据与基数按大小合并成一个数组,返回

    return quickSort(left).concat([pivot], quickSort(right))

    git 地址:  https://gitee.com/guangzhou110/front-end-sorting-algorithm

     
     
     
    越努力越幸运
  • 相关阅读:
    131. Palindrome Partitioning
    130. Surrounded Regions
    129. Sum Root to Leaf Numbers
    128. Longest Consecutive Sequence
    125. Valid Palindrome
    124. Binary Tree Maximum Path Sum
    122. Best Time to Buy and Sell Stock II
    121. Best Time to Buy and Sell Stock
    120. Triangle
    119. Pascal's Triangle II
  • 原文地址:https://www.cnblogs.com/guangzhou11/p/14495265.html
Copyright © 2011-2022 走看看