包含冒泡排序、选择排序、插入排序、归并排序、快速排序

247 阅读1分钟
// 生成测试数据
var data = Array.from({length: 20}, () => Math.floor(Math.random() * 100));

function swap(array, a, b) {
  [array[a], array[b]] = [array[b], array[a]];
}

/**
 * 冒泡排序
 * @param {number[]} array
 */
function boubleSort(array) {
  for (let i = 0; i < array.length - 1; i++) {
    for (let j = 0; j < array.length - 1 - i; j++) {
      if (array[j] > array[j + 1]) {
        swap(array, j, j + 1);
      }
    }
  }
  return array;
}

/**
 * 优化版冒泡排序
 * 如果在一轮比较中都没有交换数据,说明的数据已经排好序了,直接跳过
 * @param {number[]} array
 */
function boubleSort(array) {
  let hasChange = true;
  for (let i = 0; i < array.length - 1 && hasChange; i++) {
    hasChange = false;
    for (let j = 0; j < array.length - 1 - i; j++) {
      if (array[j] > array[j + 1]) {
        swap(array, j, j + 1);
        hasChange = true;
      }
    }
  }
  return array;
}

/**
 * 选择排序
 * @param {number[]} array 
 */
function selectSort(array) {
  for (let i = 0; i < array.length; i++) {
    let min = i;
    for (let j = i + 1; j < array.length; j++) {
      if (array[j] < array[min]) {
        min = j
      }
    }
    if (min !== i) {
      swap(array, i, min);
    }
  }
  return array;
}

/**
 * 插入排序
 * @param {number[]} array 
 */
function insertSort(array) {
  let i, j;
  let current;
  for (let i = 1; i < array.length; i++) {
    if (array[i] < array[i - 1]) {
      current = array[i];
      j = i - 1;
      for (; j >=0 && array[j] > current; j--) {
        array[j + 1] = array[j]
      }
      array[j + 1] = current;
    }
  }
  return array;
}

/**
 * 归并排序辅助方法
 * @param {number[]} a 
 * @param {number[]} b 
 */
function merge(a, b) {
  let i = 0;
  let j = 0;
  const result = [];
  while (i < a.length && j < b.length) {
    if (a[i] < b[j]) {
      result.push(a[i++]);
    } else {
      result.push(b[j++]);
    }
  }

  while (i < a.length) {
    result.push(a[i++]);
  }

  while (j < b.length) {
    result.push(b[j++]);
  }

  return result;
}

/**
 * 归并排序
 * @param {number[]} array 
 */
function mergeSort(array) {
  if (array.length <= 1) {
    return array;
  }
  const mid = Math.floor(array.length / 2);
  const left = array.slice(0, mid);
  const right = array.slice(mid);
  return merge(mergeSort(left), mergeSort(right));
}


/**
 * 快速排序
 * @param {number[]} array 
 */
function quickSort(array) {
  if (array.length <= 1) {
    return array;
  }
  const pivot = array[0];
  const left = [];
  const right = [];
  for (let i = 1; i < array.length; i++) {
    if (array[i] < pivot) {
      left.push(array[i]);
    } else {
      right.push(array[i]);
    }
  }
  
  return quickSort(left).concat(pivot, quickSort(right));
}


console.log(data);
console.log(boubleSort([...data]));
console.log(selectSort([...data]));
console.log(insertSort([...data]));
console.log(mergeSort([...data]));
console.log(quickSort([...data]));