salem saggaf
salem saggaf

Reputation: 43

Quicksort algorithm not working

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

Upvotes: 0

Views: 89

Answers (1)

k001daddy
k001daddy

Reputation: 21

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.

Upvotes: 1

Related Questions