Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

插入排序 #196

Open
Sunny-117 opened this issue Nov 3, 2022 · 1 comment
Open

插入排序 #196

Sunny-117 opened this issue Nov 3, 2022 · 1 comment

Comments

@Sunny-117
Copy link
Owner

No description provided.

@Achetto
Copy link

Achetto commented Dec 2, 2022

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为应该插入的位置
      }
      j--;
    }
    this[j] = temp;
  }
}
// 时间复杂度O(n^2)
const arr = [2,5,4,8,2,1];
arr.insertionSort();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants