简体   繁体   中英

java.lang.StackOverflowError in QuickSort code

I wrote this method for QuickSort:

public static void QuickSort(int f, int l, int a[]) 
// f, when passedfrom a method at first is equal to the first index of 
//the array, while l is the last. So if I'm passing an array of length 
//10, f=0 and l=9
{
int temp;
int mid= (int)(l+f)/2;
  for (int r=f; r<l; r++)
{ 
   if(a[r]<a[mid] && r>mid)
   {
       temp=a[r];
       a[r]=a[mid+1];
       a[mid+1]=a[mid];
       a[mid]=temp;
       mid=mid+1;

   }
   else if(a[r]>a[mid] && r<mid)
   {
       temp=a[r];
       a[r]=a[mid-1];
       a[mid-1]=a[mid];
       a[mid]=temp;
       mid=mid-1;

   }
}
  if((checksortasc(a))==false)
 {
   QuickSort(f, mid-1, a);// Exception
   QuickSort(mid+1 ,l, a);
 }
 else
  {
   for(int r=0; r<10; r++)
       System.out.println(a[r]);
   System.exit(0);

 }
}
  public static boolean checksortasc(int a[])
{ 
for(int i=0;i<a.length-1;i++){
    if(a[i]<=a[i+1])
        continue;

    return false;
}
return true;
}
}

This gave me :

Exception in thread "main" java.lang.StackOverflowError

at the line I have marked with a comment above. Why was this exception thrown and what can I do to fix my code? I am a novice, Any help is much appreciated.

The problem is using checksortasc , which will return false pretty much every time.

The logic of quicksort is to separate the array into two parts, with each element in the lower part smaller than the higher part. Then, if each part is longer than 1, apply the same process to each part.

Note that after a first separation, the array is still not sorted. The upper part, in particular, has not been sorted, so your algorithm will keep recursing at the line you commented because checksortasc keeps returning false.

Check for the difference between l and f instead; if less or equal than 1, stop recursing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM