日期:2014-05-20  浏览次数:20840 次

一个快速排序运行时出现问题?
这是代码:
-------------------------
public   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   int   partition(int[]   r,int   z,int   x){
int   i,j,temp,pivot;
i=z;
j=x+1;
pivot=r[i];
while(i <j){
while(pivot <=r[j])j--;
if(i <j){
r[i]=r[j];
i++;
}
while(pivot> =r[i])i++;
if(i <j){
r[j]=r[i];
j--;
}
}//while   end
r[i]=pivot;
return   i;
}

//快速排序结束

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();
ss.quicksort(num,0,9);
for(int   a=1;a <num.length;a++)
System.out.println(num[a]);
}
--------------------------

编译可以通过,运行出现如下错误:

--------------------------
D:\java> javac   Sort.java

D:\java> java   Sort
Exception   in   thread   "main "   java.lang.ArrayIndexOutOfBoundsException:   10
                at   Sort.partition(Sort.java:68)
                at   Sort.quicksort(Sort.java:57)
                at   Sort.main(Sort.java:98)
-----------------------------------


------解决方案--------------------
你在程序中调用时数组时越界了。

j=x+1;
r[i]=r[j];

这地方就有错
------解决方案--------------------
标准快速排序,lz参考一下;

package org.luyang.collections;

class ArrayIns {
private long[] theArray; // ref to array theArray

private int nElems; // number of data items
// --------------------------

public ArrayIns(int max) // constructor
{
theArray = new long[max]; // create the array
nElems = 0; // no items yet
}

// --------------------------
public void insert(long value) // put element into array
{
theArray[nElems] = value; // insert it
nElems++; // increment size
}

// --------------------------
public void display() // displays array contents
{
System.out.print( "A= ");
for (int j = 0; j < nElems; j++)
// for each element,
System.out.print(theArray[j] + " "); // display it
System.out.println( " ");
}

// --------------------------
public void quickSort() {
recQuickSort(0, nElems - 1);
}

// --------------------------
public void recQuickSort(int left, int right) {
if (right - left <= 0) // if size <= 1,
return; // already sorted