Public number: hand touch hand front step

1. Bubble sort
/** * compare all adjacent elements, and if the first element is larger than the second, swap them * round down to ensure that the last element is the largest * perform n-1 rounds to complete the sorting */
Array.prototype.bubbleSort = function () {
  for (let i = 0; i < this.length - 1; i++) {
    for (let j = 0; j < this.length - 1 - i; j++) {
      if (this[j] > this[j + 1{[])this[j], this[j + 1]] = [this[j + 1].this[j]]
      }
    }
  }
}

const arr = [5.4.3.3.32.1]
arr.bubbleSort()

// Time complexity: O(n^2)
// However, bubble sort has poor performance and is rarely used in work, mostly in interviews
Copy the code
2. Selection sort
/** * Finds the smallest value in the array, selects it and places it first * then finds the second-smallest value, selects it and places it second * and so on, performing n-1 rounds */
Array.prototype.selectionSort = function () {
  for (let i = 0; i < this.length - 1; i++) {
    let indexMin = i
    for (let j = i; j < this.length; j++) {
      if (this[j] < this[indexMin]) {
        indexMin = j
      }
    }
    if(indexMin ! == i) { [this[i], this[indexMin]] = [this[indexMin], this[i]]
    }
  }
}
const arr1 = [5.4.3.3.32.1]
arr1.selectionSort()
// Two nested loops, time complexity: O(n^2)
// Selection sort, like bubble sort, has poor performance and is rarely used in work, mostly in interviews
Copy the code
3. Insert sort
/** ** start with the second number and move up to the last number */

Array.prototype.insertionSort = function () {
  for (let i = 1; i < this.length; i++) {
    const temp = this[i]
    let j = i
    while (j > 0) {
      if (this[j - 1] > temp) {
        this[j] = this[j - 1]}else {
        break
      }
      j--
    }
    this[j] = temp
  }
}

const arr2 = [5.4.3.3.32.1]
arr2.insertionSort()

// Two nested loops, time complexity: O(n^2)
Copy the code