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

第 88 期(算法-排序):经典排序算法之插入排序 #91

Open
wingmeng opened this issue Aug 16, 2019 · 0 comments
Open

第 88 期(算法-排序):经典排序算法之插入排序 #91

wingmeng opened this issue Aug 16, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

插入排序

插入排序(Insertion sort)是一种简单直观且稳定的排序算法。

  • 原理: 将每次插入的数和之前已经完成排序的序列进行重新排序。
  • 复杂度: 时间复杂度:O(n²),空间复杂度:O(1)
  • 稳定性: 选插入排序是稳定的排序算法。

insertionSort

function insertionSort(arr) {
  // 注意这里是从 arr[1] 开始的
  for (var i = 1; i < arr.length; i++) {
    var preIndex = i - 1;
    var current = arr[i];
    
    while (preIndex >= 0 && arr[preIndex] > current) {
      arr[preIndex + 1] = arr[preIndex];
      preIndex--;
    }

    arr[preIndex + 1] = current;
  }

  return arr;
}
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

1 participant