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

第 87 期(算法-排序):经典排序算法之选择排序 #90

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

第 87 期(算法-排序):经典排序算法之选择排序 #90

wingmeng opened this issue Aug 15, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented Aug 15, 2019

选择排序

选择排序(Selection sort)是一种简单直观的排序算法。

  • 原理: 从待排序的元素中选出最大或最小的元素放到已排序好的元素后面。
  • 复杂度: 时间复杂度:O(n²),空间复杂度:O(1)
  • 稳定性: 选择排序是不稳定的排序算法。

selectionSort

function selectionSort(arr) {
  var len = arr.length;
  var minIndex, temp;

  for (var i = 0; i < len - 1; i++) {
    minIndex = i;

    for (var j = i + 1; j < len; j++) {
      if (arr[j] < arr[minIndex]) {  // 寻找最小的数
        minIndex = j;  // 将最小数的索引保存
      }
    }

    temp = arr[i];
    arr[i] = arr[minIndex];
    arr[minIndex] = 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