Skip to content

选择排序

遍历数组,每次将最值放入索引 i 处. 时间复杂度 O(n^2).

Code

javascript
const { exchange } = require('./common.js');

function selectSort(nums) {
  for (let i = 0; i < nums.length - 1; i++) {
    for (let j = i + 1; j < nums.length; j++) {
      if (nums[j] < nums[i]) {
        exchange(nums, i, j);
      }
    }
  }
}

Test Case

javascript
const { selectSort } = require('./selectSort');
describe('mergeSort', () => {
  it('case1', () => {
    const nums = [3, 2, 5, 7, 8, 9, 0, 6];
    const expected = [0, 2, 3, 5, 6, 7, 8, 9];
    selectSort(nums);
    expect(nums).toEqual(expected);
  });
  it('case2', () => {
    const nums = [];
    const expected = [];
    selectSort(nums);
    expect(nums).toEqual(expected);
  });
  it('case3', () => {
    const nums = [1];
    const expected = [1];
    selectSort(nums);
    expect(nums).toEqual(expected);
  });
  it('case4', () => {
    const nums = [1, 2];
    const expected = [1, 2];
    selectSort(nums);
    expect(nums).toEqual(expected);
  });
});