快速排序,但是一直报如下错误;
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
代码如下:
/**
* @Description 快速排序
**/
public class QuickSort {
public static void main(String[] args) {
int[]a = {2,1,5,7,9,0,6,4,3,8};
doSort(a,0,a.length-1);
System.out.println(a);
}
private static void doSort(int[] a, int lo, int hi) {
int j = partition(a,lo,hi);
doSort(a,lo,j-1);
doSort(a,j+1,hi);
}
private static int partition(int[] a, int lo, int hi) {
int i = lo,j = hi+1;
int v = a[lo];
while (true){
while (a[++i]<v) if(i==hi)break;
while (a[--j] >v) if(j==lo) break;
if(i>=j) break;
swap(a,i,j);
}
swap(a,lo,j);
return j;
}
private static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
package com.ctsing.emsm.test;
public class Test {
public static void main(String[] args) {
int[]a = {2,1,5,7,9,0,6,4,3,8};//下标0-9
System.out.print("原来的数组a:");
for(int s:a) {
System.out.print(s+" ");
}
System.out.println();
doSort(a,0,a.length-1);
}
private static void doSort(int[] a, int lo, int hi) {
System.out.println("doSort--lo:"+lo+",hi:"+hi);
int j = partition(a,lo,hi);
doSort(a,lo,j-1);
doSort(a,j+1,hi);
}
private static int partition(int[] a, int lo, int hi) {
System.out.println("partition--lo:"+lo+",hi:"+hi);
int i = lo,j = hi+1;
System.out.println("i:"+i+",j+1:"+j);
int v = a[lo];
System.out.println(v);
while (true){
while (a[++i]<v) if(i==hi)break;
System.out.println("while--i:"+i);
while (a[--j] >v) if(j==lo) break;
System.out.println("while--j:"+j);
if(i>=j) break;
swap(a,i,j);
}
swap(a,lo,j);
System.out.println("获取j:"+j);
return j;
}
private static void swap(int[] a, int i, int j) {
System.out.println("swap:"+i+","+j);
int temp = a[i];
a[i] = a[j];
a[j] = temp;
System.out.print("现在的数组a:");
for(int s:a) {
System.out.print(s+" ");
}
System.out.println();
}
}
原来的数组a:2 1 5 7 9 0 6 4 3 8
doSort--lo:0,hi:9
partition--lo:0,hi:9
i:0,j+1:10
2
while--i:2
while--j:5
swap:2,5
现在的数组a:2 1 0 7 9 5 6 4 3 8
while--i:3
while--j:2
swap:0,2
现在的数组a:0 1 2 7 9 5 6 4 3 8
获取j:2
doSort--lo:0,hi:1
partition--lo:0,hi:1
i:0,j+1:2
0
while--i:1
while--j:0
swap:0,0
现在的数组a:0 1 2 7 9 5 6 4 3 8
获取j:0
doSort--lo:0,hi:-1
partition--lo:0,hi:-1
i:0,j+1:0
0
while--i:1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at com.ctsing.emsm.test.Test.partition(Test.java:32)
at com.ctsing.emsm.test.Test.doSort(Test.java:17)
at com.ctsing.emsm.test.Test.doSort(Test.java:18)
at com.ctsing.emsm.test.Test.doSort(Test.java:18)
at com.ctsing.emsm.test.Test.main(Test.java:12)