简体   繁体   中英

QuickSort java.lang.StackOverflowError

I am trying to calculate the execution time of quicksort algorithm in three cases "Mid pivot, first pivot, random pivot" of an array was already sorted.

The mid pivot and random works fine with any size, but the first pivot case gives stackoverflow if the size was greater than 25000.

Heres the code:

static void q_sort( int left, int right)
{

int pivot;
int l_hold, r_hold;

  l_hold = left;
  r_hold = right;
  pivot = array[left];
  while (left < right)
  {
    while ((array[right] >= pivot) && (left < right))
      right--;
    if (left != right)
    {
      array[left] = array[right];
      left++;
    }
    while ((array[left] <= pivot) && (left < right))
      left++;
    if (left != right)
    {
      array[right] = array[left];
      right--;
    }
  }
  array[left] = pivot;
  pivot = left;
  left = l_hold;
  right = r_hold;
  if (left < pivot)
    q_sort(left,(int) pivot-1);
  if (right > pivot)
    q_sort( (int)pivot+1, right);
}

and heres the calling code:

double startTime1 = System.currentTimeMillis();
q_sort(0,size -1);
double stopTime1 = System.currentTimeMillis();
double elapsedTime1 = stopTime1 - startTime1;      
System.out.println(elapsedTime1);

You didn't tell how the array was generated, but I suspect it was already sorted.

The problem is the following: if you quicksort an already sorted array, the first pivot causes the following recursion: 0..24999, 1..24999, 2..24999, 3..24999, 4..24999 which takes a lot of stack space and results in a stack overflow. This is because the array is 0..24999 and the pivot is 0, and the second partition then will become 1..24999.

You should eliminate one of the tail calls. Which tail call to eliminate depends on which partition is smaller. You want the recursion to process as little data as possible. One of the recursions is simply replaced by a loop. This tail recursion elimination has already been explained at Quicksort and tail recursive optimization

Anyway, I recommend using an existing quicksort algorithm instead of coding it yourself unless this is a homework question.

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