AVC
AVC

Reputation: 61

Stack overflow when I implement Quicksort method

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);
    }
}

Upvotes: 1

Views: 76

Answers (1)

AVC
AVC

Reputation: 61

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);

Upvotes: 1

Related Questions