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

100.选择排序 #100

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

100.选择排序 #100

webVueBlog opened this issue Mar 3, 2023 · 0 comments

Comments

@webVueBlog
Copy link
Member

原理

从未排序的序列中找到最大(或最小的)放在已排序序列的末尾(为空则放在起始位置),重复该操作,直到所有数据都已放入已排序序列中。

var selectionSort = function (arr) {
 const n = arr.length;

 for (let i = 0; i < n - 1; i++) {
  // 最小值的下标
  let min = i;
  
  // 找到 i 之后的最小值
  for (let j = i+1; j < n; j++) {
    if (arr[j] < arr[min]) {
      min = j
    }
  }

  // 交换位置
  if (i !== min) {
   const temp = arr[i];
   arr[i] = arr[min];
   arr[min] = temp;
  }
 }
 
 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