快速排序的核心框架是“二叉树的前序遍历+对撞型双指针”。
快速排序的实现1:
public void quickSort(int[] arr, int left, int right) {if (left < right) {// pivot将遍历的范围限制在了pivot之前int pivot = arr[right];int i = left - 1;for (int j = left; j < right; j++) {if (arr[j] < pivot) {i++;int temp = arr[i];arr[i] = arr[j];arr[j] = temp;}}// 哨兵移动到pivotIndex上int pivotIndex = i + 1;int temp = arr[pivotIndex];arr[pivotIndex] = arr[right];arr[right] = temp;quickSort(arr, left, pivotIndex - 1);quickSort(arr, pivotIndex + 1, right);}
}
快速排序的实现2:
public void quickSort(int[] array, int start, int end) {if (start >= end) {return;}int left = start, right = end;int pivot = array[(start + end) / 2];while (left <= right) {while (left <= right && array[left] < pivot) {left++;}while (left <= right && array[right] > pivot) {right--;}if (left <= right) {int temp = array[left];array[left] = array[right];array[right] = temp;left++;right--;}}quickSort(array, start, right);quickSort(array, left, end);
}
如果对您有帮助,请点赞关注支持我,谢谢!❤
如有错误或者不足之处,敬请指正!❤
个人主页:星不易 ❤
算法通关村专栏:不易|算法通关村 ❤