0

so this is my first time posting something in stackoverflow

i was trying to implement the quicksort algorithm but when i compile the code and try to run it hangs

so this is the code

#include <iostream>
using namespace std;

void swap(int& num1,int& num2)
{
    int temp = num2;
    num2 = num1;
    num1 = temp;
}

int partitionTest(int arr[],int p,int r)
{
    int i = p;
    for(int j =p ;j<r-1;j++)
    {
        if(arr[j]> arr[r-1])
        {
            i++;
            swap(arr[j],arr[r-1]);
        }
        swap(arr[i],arr[r]);
        return i;
    }
}

void quicksort(int arr[],int p,int r )
{
    if (p < r)
    {
        int temp = partitionTest( arr, p, r );
        quicksort( arr, p, temp - 1 );
        quicksort( arr, temp + 1, r );
    }

}


int main()
{
    int arr[5]={5,4,3,2,1};

    quicksort(arr,0,4);

    cout << arr[0] << " ";
    cout << arr[1] << " ";
}

i would appreciate any kind of help

4
  • 3
    You should probably look into stepping through your code with a debugger to see where the error is occurring and look at the program state at that time. Commented Feb 2, 2016 at 15:42
  • 4
    Returning something in a loop will halt the loop and leave the method and you're calling it unconditionally. Commented Feb 2, 2016 at 15:47
  • 1
    You're returning in the first iteration of each forloop Commented Feb 2, 2016 at 15:47
  • 1
    You seem to not have made up your mind about whether r is the greatest valid index or "one past" the greatest valid index. (Test your partitioning function on its own first.) Commented Feb 2, 2016 at 15:50

1 Answer 1

1

Three recursions into quicksort(), the p=3 and r=4. The for condition in partitionTest() says if j<r-1, which turns into 3<3 and the loop is never executed. The function exits without a return value, so temp is undefined.

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

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.