快速排序 while (left = right && arr【right】 pivot) right--;
这行代码 &&左右条件换位置后
待排序数组为int【】 arr = {7,3,5,6}; 时 会报错
Index -1 out of bounds for length 4
提示 right 为-1
而不换位置即使right 为-1 也不报错 为什么啊
代码详情
package digui;
public class QuickSort {
public static void main(String[] args){
int[] arr = {7,3,5,6};
sort(arr,0,arr.length-1);
D01.print(arr);
}
public static void sort(int[] arr,int leftBound,int rightBound){
if(leftBound >= rightBound) return;
int mid = partition(arr,leftBound,rightBound);
sort(arr,leftBound,mid - 1);
sort(arr,mid + 1,rightBound);
}
static int partition(int[] arr,int leftBound,int rightBound){
int pivot = arr[rightBound];
int left = leftBound;
int right = rightBound - 1;
while (left <= right){
** while (left <= right && arr[left] <= pivot) left++;
while (left <= right && arr[right] > pivot) right--;
![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/743177670036192.png '1.png')
**
System.out.println("Right"+right);
if(left < right) swap(arr,left,right);
}
swap(arr,left,rightBound);
return left;
}
static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}