常见排序记录

1、冒泡排序

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

2、选择排序

// 每次找出剩余数中最小的一个,替换位置
function sectionSort(arr) {
  let len = arr.length;
  let minIndex;
  for (let i = 0; i < len; i++) {
    minIndex = i;
    for (let j = i + 1; j < len; j++) {
      if (arr[j] < arr[minIndex]) {
        minIndex = j;
      }
    }
    if (minIndex !== i) {
      [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
    }
  }
  return arr;
}

  

3、插入排序

function insertionSort(arr) {
  let len = arr.length;
  let preIndex, current;
  for (let i = 1; i < len; i++) {
    preIndex = i - 1;
    current = arr[i];
    while(preIndex >= 0 && arr[preIndex] > current) {
      arr[preIndex + 1] = arr[preIndex];
      preIndex--;
    }
    arr[preIndex + 1] = current;
  }
  return arr;
}
function insertion(array) {
  for (let i = 1; i < array.length; i++) {
    for (let j = i - 1; j >= 0 && array[j] > array[j + 1]; j--)
        [arr[j], arr[j + 1]] = arr[j + 1], arr[j]
  }
  return array;
}

4、快速排序

function quickSort(arr) {
  if (arr.length <= 1) {
    return arr;
  }

  let left = [];
  let right = [];
  let current = arr.pop();
  let len = arr.length;

  for (let i = 0; i < len; i++) {
    if (arr[i] < current) {
      left.push(arr[i]);
    } else {
      right.push(arr[i]);
    }
  }

  return quickSort(left).concat(current, quickSort(right));
}

5、归并排序

function mergeSort(arr, start, end) {
  if (start > end) {
    return [];
  } else if (start == end) {
    return [arr[start]];
  }

  let center = Math.floor((start + end) / 2);
  let left = mergeSort(arr, start, center);
  let right = mergeSort(arr, center + 1, end);

  let result = [];
  while (left.length > 0 || right.length > 0) {
    if (left[0] < right[0]) {
      result.push(left.shift());
    } else {
      result.push(right.shift());
    }

    if (left.length == 0) {
      result = result.concat(right);
      break;
    } else if (right.length == 0) {
      result = result.concat(left);
      break;
    }
  }
  return result;
}

  

posted on 2020-05-04 00:40  StephenWong  阅读(161)  评论(0编辑  收藏  举报