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

选择排序 #9

Open
HerokunTan opened this issue Dec 13, 2020 · 0 comments
Open

选择排序 #9

HerokunTan opened this issue Dec 13, 2020 · 0 comments

Comments

@HerokunTan
Copy link
Owner

HerokunTan commented Dec 13, 2020

selectSort

时间复杂度:O(n2
空间复杂度:O(1)
非稳定排序
原地排序

const TYPE = {
  asc: Symbol('asc'),//升序
  des: Symbol('des')//降序
};

let testArr =  [8,5,2,6,9,3,1,4,0,7]

function selectSort(arr,type) {
  const n = arr.length;
  let tem = -Number.MAX_VALUE;
  for (let i = 0; i < n - 1; i++) {
    let flag = false;
    for (let j = i + 1; j < n; j++) {
      if (type===TYPE.asc?arr[j] < arr[i]:arr[i] < arr[j]) {
        flag = true 
        tem = arr[j];
        arr[j] = arr[i];
        arr[i] = tem;
      }
    }
    if(!flag) break; //如果没有发生过位置交换,之后就是有序了,不在遍历
  }
  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