lewenweijia / notes

🏊 dive dive diving
1 stars 0 forks source link

算法实现: (基于比较的排序基础算法) 插入/选择/冒泡 (insertion/selection/bubble) #15

Open lewenweijia opened 5 years ago

lewenweijia commented 5 years ago
// insertion/selection/bubble
// hint: all is inplace opeartion
// time complexity: O(n^2), n is input size
// 都是基于比较的排序方法的哦
// 都是原地修改的算法的呢, 都是O(n^2)的复杂度的额,哈哈
// 冒泡和选择?: 都是固定一位进行元素选择呢, 而插入则是固定一位移动3

function insertionSort(arr) {
  for (let i = 1; i < arr.length; i++) {
    for (let j = i; j > 0; j--) {
      if (arr[j] < arr[j - 1]) {
    [arr[j], arr[j - 1]] = [arr[j - 1], arr[j]];
      } else {
    break;
      }
    }
  }

  return arr;
}

function bubbleSort(arr) {
  for (let i = 0; i < arr.length - 1; i++) { // define times
    let hasSwap = false;
    for (let j = 0; j < arr.length - i - 1; j++) { // adjacent element comparison
      if (arr[j] > arr[j +1]) {
    [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
    hasSwap = true;
      }
    }

    if (!hasSwap) break;
  }

  return arr;
}

function selectionSort(arr) {
  for (let i = 0; i < arr.length - 1; i++) {
    let idx = i;
    for (let j = i; j < arr.length; j++) {
      if (arr[idx] > arr[j]) idx = j;
    }

    [arr[i], arr[idx]] = [arr[idx], arr[i]];
  }

  return arr;
}