快速排序

174 阅读1分钟
const list = [3, 12, 7, 10, 9, 5, 8, 1, 11, 4, 6];

// 快速
function findMidIndex(arr, start, end) {
  let i = start; // 最左边
  let j = end; // 最右边
  const pivot = arr[end]; // 用最后一个值最为基准
  let p = true; // small: true   // 钟摆

  while (i < j) {
    console.log('【while】', i, j, p, arr);
    find();
  }
  if (i === j) {
    console.log('最终结果midIndex', i);
    return i;
  }
  function find() {
    if (p) {
      while (arr[i] < pivot) {
        i++;
      }

      if (arr[i] > pivot) {
        [arr[i], arr[j]] = [arr[j], arr[i]];
        j--;
        p = false;
      }
    } else {
      while (pivot < arr[j]) {
        j--;
      }

      if (pivot > arr[j]) {
        [arr[i], arr[j]] = [arr[j], arr[i]];
        i++;
        p = true;
      }
    }
    if (i === j) {
      return i;
    }
  }
}

function quickSort(arr, start, end) {
  console.log('start:', start, 'end:', end);
  if (start >= end) return;
  const midIndex = findMidIndex(arr, start, end);
  console.log('midIndex', midIndex);
  quickSort(arr, start, midIndex - 1);
  quickSort(arr, midIndex + 1, end);
}

quickSort(list, 0, list.length - 1);
console.log('最终排序后的数组:', list);