数据结构_快速排序

shenwenjie 2020-02-26

//快速排序
  class ArrayList {
    constructor () {
      this.array = []
    }
    insert (data) {
      return this.array.push(data)
    }
    quickSort () {
      this.array = this.quick(this.array)
    }
    //辅助函数
    quick (arr) {
      let length = arr.length
      if (length <= 1) return arr
      let pivotValue = arr.splice(Math.floor(length / 2), 1)[0]
      let leftArr = []
      let rightArr = []
      for (let i = 0; i < arr.length; i++) {
        if (arr[i] < pivotValue) leftArr.push(arr[i])
        else rightArr.push(arr[i])
      }
      return this.quick(leftArr).concat(pivotValue, this.quick(rightArr))
    }
  }
  let arr = new ArrayList()
  arr.insert(9)
  arr.insert(5)
  arr.insert(8)
  arr.insert(0)
  arr.insert(1)
  arr.insert(6)
  arr.insert(4)
  arr.insert(7)
  arr.insert(3)
  arr.insert(2)

相关推荐