public class QuickSort {
public static void main(String[] args) {
int[] num={2,4,7,9,1,8,3,0,5,6};
quickSort(num,0,9);
for(int i=0;i<10;i++)
System.out.println(num[i]);
}
public static void quickSort(int a[], int l, int r)
{
if (l >= r) return;
int i = l;
int j = r + 1;
int pivot = a[l];
while (true)
{
do
{
i = i + 1;
} while (a[i] < pivot);
do
{
j = j - 1;
}
while (a[j] > pivot);
if (i >= j) break;
swap(a[i], a[j]);
}
a[l] = a[j];
a[j] = pivot;
quickSort(a, l, j-1);
quickSort(a, j+1, r);
}
public static void swap(int x,int y)
{
int temp=x;
x=y;
y=temp;
}}总是报错
java.lang.ArrayIndexOutOfBoundsException: 10
at QuickSort.quickSort(QuickSort.java:20)
at QuickSort.quickSort(QuickSort.java:34)
at QuickSort.quickSort(QuickSort.java:34)
at QuickSort.main(QuickSort.java:5)
Exception in thread "main" 对java的异常不是很了解,怎么修改才行?
解决方案 »
- 二叉树算法,中的中树遍历很是不理解,求指点。
- 求助!在本地的eclipse和虚拟机上compile没问题,可老是在服务器上compile不过
- java 开发ERP效果
- 关于String对象在内存中的存活 (与其他问题不同)
- JDK里面的有些代码是不是不能看啊
- 问下各位关于华为对应届本科生的要求
- 急呀!求救,散分,反编译的一个CLASS文件,怎样把它编辑成可用的代码
- java程序里面如何打开一个网页链接?
- 有那位用java写过读取com口的程序(就是银行取钱的时候用密码键盘输入的那种)谢谢!
- 大家推荐几本学习JAVA的书好吗?
- java.sql.SQLException: Io 异常: Broken pipe 什么意思?
- 怎样在xml里写Java代码?
肯定是在这里面出错
do
{
i = i + 1;
} while (a[i] < pivot);
do
{
j = j - 1;
}
while (a[j] > pivot);
if (i >= j) break;
swap(a[i], a[j]);
{
j = j - 1;
}
while (a[j] > pivot);
先执行了j=j-1不就不越界了吗
{
i = i + 1;
} while (i < j && a[i] < pivot);
这样应该就没有问题了
public class Test
{
public static void main(String arge[]){
int [] num=new int[10];
num[0]=111;
num[1]=68;
num[2]=18;
num[3]=38;
num[4]=88;
num[5]=98;
num[6]=78;
num[7]=58;
num[8]=48;
num[9]=28;
//Sort ss=new Sort();
quicksort(num,0,9);
for(int a=0;a<num.length;a++)
System.out.println(num[a]);
}
public static void quicksort(int[] r,int low,int high){
int pivo;
if(low<high){
pivo=partition(r,low,high);
quicksort(r,low,pivo-1);
quicksort(r,pivo+1,high);
}
}
public static int partition(int[] r,int z,int x){
int i,j,temp,pivot;
i=z;
j=x;
pivot=r[i];
while(i<j){
while(i < j && pivot<=r[j]) j--;
if(i<j){
r[i]=r[j];
i++;
}
while(i < j && pivot>=r[i]) i++;
if(i<j){
r[j]=r[i];
j--;
}
}//while end
r[i]=pivot;
return i;
}}
数组越界
肯定是在这里面出错
do
{
i = i + 1;
} while (a[i] < pivot);
do
{
j = j - 1;
}
while (a[j] > pivot);
if (i >= j) break;
swap(a[i], a[j]);
-------------------------------------------------
不懂楼主这段程序是怎么写的?你是不是考虑下在while里试着加个条件
if(i>=num.length) break;
{
j = j - 1;
}
while (a[j] > pivot);
先执行了j=j-1不就不越界了吗
------------------------
我晕了,你的数组长度是9,j = r + 1; 这时候j=10;
j=j-1; 这时候j=9;
num[9]还没越界?