quicksort,

why this code makes error

publicclass QuickSort

{

publicstaticint cutoff=3;

staticint[]arr=newint[10];

publicstaticvoid swap(int []A,int x,int y)

{

int temp=0;

temp=A[x];

A[x]=A[y];

A[y]=temp;

}//end swap function

publicstaticint median3(int[]A,int left,int right)

{

int Center=(left+right)/2;

if(A[left]>A[Center])

swap(A,left,Center);

if(A[left]>A[right])

swap(A,left,right);

if(A[Center]>A[right])

swap(A,Center,right);

swap(A,Center,right-1);

return A[right-1];

}

publicstaticvoid QuickSort(int[]A,int left,int right)

{

int i,j;

int pivot;

//if(left+cutoff<=right)

//{//}

pivot=median3(A,left,right);

i=left;

j=right-1;

for(;;)

{ System.out.println("left="+ left+" right="+right+"i= "+i+" "+"j= "+j+" A.length="+A.length);

try{

while(A[++i]<pivot){}

//System.out.println("xxleft="+ left+" right="+right+"i= "+i+" "+"j= "+j+" A.length="+A.length);

while(A[--j]<pivot){}

}catch(Exception e){System.out.println("left="+ left+" right="+right+"i= "+i+" "+"j= "+j+" A.length="+A.length);}

if(i<j)

swap(A,i,j);

else

break;

}//end for

swap(A,i,right-1);

QuickSort(A,left,i-1);

QuickSort(A,i+1,right);

}//end QuicSort Constructor

publicstaticvoid main(String[]args)

{

int i=0;;

int[]arr=newint[10];

int j=0;

for( i=10;i>0;i--)

{

arr[j]=i;

j++;

}

QuickSort(arr,0,arr.length-1);

for(i=0;i<arr.length;i++)

System.out.println(arr[i]);

}//end main function

}//end class

">

[4696 byte] By [go2000a] at [2007-10-1 21:57:50]
# 1

impossible to tell - no comments in code, no apparent purpose to code. No mention of errors generated.

What does your debugger say? What do you get when you trace through an example?

If you have no debugger, write a routine to dump out the array and the values of the i and j pointer and look at what happens to the array at every step.

I assure you that if you dump the array, and the values i and j (not left and right as you are currenly doing) you will very quickly see why your routine is just randomizing the array.

Enjoy!

marlin314a at 2007-7-13 8:01:45 > top of Java-index,Other Topics,Algorithms...