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

97.插入排序 #97

Open
webVueBlog opened this issue Mar 3, 2023 · 0 comments
Open

97.插入排序 #97

webVueBlog opened this issue Mar 3, 2023 · 0 comments

Comments

@webVueBlog
Copy link
Member

// 原理
// 通过构建有序序列,对于排序的数据,在已知排序序列中从后往前扫描
// 找到相应的位置插入
// 时间复杂度 O(n^2)

function insertSort(arr) {
 let n = arr.length;
 let preIndex, current;

 // 从第一个开始
 for (let i = 1; i < n; i++) {
  // 前一个元素的位置
  preIndex = i - 1;
  // 当前元素
  current = arr[i];
  
  while(preIndex >= 0 && arr[preIndex] > current) {
   arr[preIndex + 1] = arr[preIndex];
   preIndex--;
  }
  
  // 假如 pre cur [1,2]
  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