SOURCE

class ArrayList {
  constructor() {
      this.array = []
  }
  insert(item) {
      this.array.push(item)
  }
  toString() {
      return this.array.join()
  }
  // 私有函数 交换
  _swap(index1, index2) {
      let aux = this.array[index1]
      this.array[index1] = this.array[index2]
      this.array[index2] = aux
  }
  // 快速排序
  quick(left, right) {
      let index
      if(this.array.length > 1) {
          index = this._partition(left, right)
          if(left < index - 1) {
              this.quick(left, index - 1)
          }
          if(index < right) {
              this.quick(index, right)
          }
      }
      // return this.array
  }
  // 划分
  _partition(left, right) {
      let pivot = this.array[Math.floor((right + left) / 2)]
      let i = left
      let j = right
      while(i <= j) {
          while(this.array[i] < pivot) {
              i++
          }
          while(this.array[j] > pivot) {
              j--
          }
          if(i <= j) {
              this._swap(i, j)
              i++
              j--
          }
      }
      return i
  }
  // 二分搜索
  binarySearch(item) {
      // 快速排序
      this.quick(0, this.array.length - 1)
      let low = 0
      let high = this.array.length - 1
      let mid, element
      while(low <= high) {
          mid = Math.floor((low + high) / 2)
          element = this.array[mid]
          if(element < item) {
              low = mid + 1
          } else if(element > item) {
              high = mid - 1
          } else {
              return mid
          }
      }
      return -1
  }
}
const arr = new ArrayList()
arr.insert(1000)
arr.insert(27)
arr.insert(4)
arr.insert(135)
console.log(arr.array)
console.log(arr.binarySearch(4))
console 命令行工具 X clear

                    
>
console