1

Hello I am trying to implement Quicksort method in Java, but for some reason I am getting a stack overflow error when I am doing as little as 5 elements! Any ideas what could be wrong? Part of my Code:

class QuickSort implements AbstractSort {
    public int partition(int[] numbers, int start, int end)
    {
        int pivot = numbers[end];
        int theIndex = start;
        int temp;
        for(int i = start; i <= end - 1; i++)
        {
            if(numbers[i] <= pivot)
            {
                temp = numbers[theIndex];
                numbers[theIndex] = numbers[i];
                numbers[i] = temp;
                theIndex++;
            }
        }
        temp = numbers[theIndex];
        numbers[theIndex] = pivot;
        numbers[end] = temp;
        return theIndex;
    }

    public void mySort(int[] numbers, int start, int end)
    {
        if(start < end)
        {
            int myIndex = partition(numbers, start, end);

            mySort(numbers, 0, myIndex-1);
            mySort(numbers, myIndex + 1, numbers.length - 1);
        }
        else
        {
            return;
        }
    }
    public void sort(int[] numbers) 
    {
        mySort(numbers, 0, numbers.length - 1);
    }
}
2
  • can you provide some examples that your are trying to sort? Commented Nov 19, 2015 at 3:00
  • I used 9 0 8 5 6 ... But I have figured out the problem! I should not pass 0 in my recursion quicksort, but "start". so instead of mySort(numbers, 0, myIndex-1); it should be mySort(numbers, start, myIndex-1); Commented Nov 19, 2015 at 3:05

1 Answer 1

1

The problem was in mySort(numbers, 0, myIndex-1); I should be putting start instead of a 0, so the correct code looks like this mySort(numbers, start, myIndex-1);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.