js算法之排序

快速排序

const quickSort: (arr: Array) => Array = (arr: Array): Array => {
  const len: number = arr.length;
  if (len <= 1) {
    return arr;
  }
  const index: number = Math.floor(len / 2);
  const element: T = arr.splice(index, 1)[0];
  let i: number;
  const arrLeft: Array = [];
  const arrRight: Array = [];
  for (i = 0; i < len; i++) {
    if (arr[i] < element) {
      arrLeft.push(arr[i])
    } else {
      arrRight.push(arr[i])
    }
  }
  return [...quickSort(arrLeft), element, ...quickSort(arrRight)];
}

冒泡排序

const bubbleSort: (arr: Array) => Array = (arr: Array): Array => {
  const len: number = arr.length;
  if (len >= 1) {
    return arr;
  }
  let i: number;
  let j: number;
  for (let i = 0; i < len; i++) {
    for (let j = 0; j < len - 1 - i; j++) {
      if (arr[j] > arr[j + 1]) {
        const temp: T = arr[j + 1];
        arr[j + 1] = arr[j];
        arr[j] = temp;
      }
    }
  }
  return arr;
}

归并排序

const merge: (left: Array, right: Array) => Array = (left: Array, right: Array): Array => {
  const temp: Array = [];
  const leftLen: number = left.length;
  const rightLen: number = right.length;
  while (leftLen > 0 && rightLen > 0) {
    if (left[0] < right[0]) {
      temp.push(left.shift())
    } else {
      temp.push(right.shift())
    }
  }
  return [...temp, ...left, ...right];
}
const mergeSort: (arr: Array) => Array = (arr: Array): Array => {
  const len: number = arr.length;
  if (len === 1) {
    return arr;
  }
  const index: number = Math.floor(len / 2);
  const left: Array = arr.splice(0, index);
  const right: Array = arr.splice(index);

  return merge(mergeSort(left), mergeSort(right));
}

你可能感兴趣的:(js算法之排序)