0

I have this function which does recursive selection sort for an array:

void  SelectionSort::RecursiveSort(int ar[] , int flag, int first, int last){
    // first - index of first element and last - index of last element
    if (flag == 1)
    {
        if (first < last)               //ascending
        {
            for (int i = first; i <= last; i++) if (ar[i] < ar[first]) swap(ar[i], ar[first]);

            RecursiveSort(ar, flag, first + 1, last);
        }
        if (first == last) return;

    }
    else
    {
        if (first < last)                   //desc
        {
            for (int i = first; i <= last; i++) if (ar[i] > ar[first]) swap(ar[i], ar[first]);

            RecursiveSort(ar,flag, (first + 1), last);
        }
        if (first == last) return;

    }
}

It works fine if array size is 3000, but I am supposed to make this work for size>5000 and its crashing giving stack overflow.

I searched many threads and they all tell to use vectors and I have. This is an assignment problem, so I am supposed to do recursion sorting for both arrays and vectors. Its working for vectors, but not for arrays. Also I am not supposed to use pointers in this assignment.

1
  • 3
    Google how to increase your stack with the compiler you use Commented Oct 18, 2015 at 17:41

2 Answers 2

1

You can try to use tail recursion, so compiler will optimize it as loop for you:

void AscRecursiveSort(int ar[], int first, int last) {
    if (first >= last) return;
    for (int i = first; i <= last; i++) if (ar[i] < ar[first]) swap(ar[i], ar[first]);
    AscRecursiveSort(ar, first + 1, last);

}

void DescRecursiveSort(int ar[], int first, int last) {
    if (first >= last) return;
    for (int i = first; i <= last; i++) if (ar[i] > ar[first]) swap(ar[i], ar[first]);
    DescRecursiveSort(ar, first + 1, last);
}

void RecursiveSort(int ar[], int flag, int first, int last) {
    // first - index of first element and last - index of last element
    if (flag == 1)
        AscRecursiveSort(ar, first, last);              //ascending
    else
        DescRecursiveSort(ar, first, last);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the tail recursion..I solved the problem by increasing the stack size in visual studio.
@ChiranthBs note of someone else will need to compile your program he'll need to do that too. That's why it's considered bad practice
1

If your compiler does not optimize tail-recursion, that solution will not work and you will need to rewrite as a while loop that checks for the base case. Not posting a complete solution because this looks like homework.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.