Elegant-JavaScript-Sorting-Algorithms icon indicating copy to clipboard operation
Elegant-JavaScript-Sorting-Algorithms copied to clipboard

冒泡排序优化,还有一种方式,设置守卫

Open Liugq5713 opened this issue 6 years ago • 0 comments

当遍历一下数组没有发生交换的时候,此时数组已经完成排序,直接返回

export const bubbleWithGuard = arr => {
  let i = arr.length - 1;
  while (i > 0) {
    let guard = true;
    let pos;
    for (let j = 0; j < i; j++) {
      if (arr[j] > arr[j + 1]) {
        pos = j;
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
        guard = false;
      }
    }
    if (guard) {
      return arr;
    }
    i = pos;
  }
  return arr;
};

Liugq5713 avatar Aug 14 '19 03:08 Liugq5713