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

选择排序 #184

Open
louzhedong opened this issue Dec 31, 2019 · 0 comments
Open

选择排序 #184

louzhedong opened this issue Dec 31, 2019 · 0 comments

Comments

@louzhedong
Copy link
Owner

louzhedong commented Dec 31, 2019

算法名称

选择排序

实现思路

  • 从头遍历到尾部,找出所有项中最大的一个元素
  • 将这个元素和第一个元素交换
  • 对剩下的元素重复进行上面的操作,每次找出剩余中最大的
  • 最后的数组是降序排列的

算法分析

总共需要进行length * (length - 1) / 2 次比较,所以时间复杂度为O(n^2),因为只需要有两个存放常量的空间,元素本身在原数组上进行交换,所以空间复杂度为O(1)

算法实现

/**
 * 选择排序
 * @param {*} array 
 */
function SelectionSort(array) {
  var length = array.length;
  for (var i = 0; i < length; i  ) {
    var maxIndex = i;
    var max = array[i];
    for (var j = i   1; j < length; j  ) {
      if (array[j] > max) {
        maxIndex = j;
        max = array[j];
      }
    }
    if (maxIndex > i) {
      var temp = array[i];
      array[i] = array[maxIndex];
      array[maxIndex] = temp;
    }

  }
}
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