Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

写一个快排 #28

Open
Liqiuyue9597 opened this issue Aug 15, 2020 · 2 comments
Open

写一个快排 #28

Liqiuyue9597 opened this issue Aug 15, 2020 · 2 comments

Comments

@Liqiuyue9597
Copy link
Owner

No description provided.

@Liqiuyue9597
Copy link
Owner Author

Liqiuyue9597 commented Sep 1, 2020

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

  var pivotIndex = Math.floor(arr.length / 2),
    pivot = arr.splice(pivotIndex, 1)[0];
  var left = [],
    right = [];
  for (var i = 0; i < arr.length; i++) {
    if (pivot > arr[i]) {
      left.push(arr[i]);
    } else {
      right.push(arr[i]);
    }
  }

  return quickSort(left).concat([pivot], quickSort(right));
}

@Liqiuyue9597
Copy link
Owner Author

Liqiuyue9597 commented Sep 1, 2020

方法二,优化递归

function quickSort1(array, left, right) {
  // 最开始不输入left和right参数
  var left = typeof left == "number" ? left : 0,
    right = typeof right == "number" ? right : array.length - 1;

  if (left < right) { //只要左指针不小于右指针就继续partition
    var index = partition(array, left, right);
    quickSort1(array, left, index - 1);
    quickSort1(array, index + 1, right);
  }
  return array;
}

var partition = function (array, left, right) {
  var pivot = array[Math.floor((right + left) / 2)];
  while (left <= right) {
    while (array[left] < pivot) {
      left++;
    }
    while (array[right] > pivot) {
      right--;
    }
    if (left <= right) {
      [array[left], array[right]] = [array[right], array[left]];
      left++;
      right--;
    }
  }
  return left;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant