0

I am trying to perform quicksort using C++ library partition function, Here's my code

int p;
int pred(int x)
{
    return x<=p;
}

    void quickSort(vector<int>::iterator first,vector<int>::iterator last) {
    if(first == last)
        return;
    if((first+1) == last)
        return;
    p = *first;
    auto mid = partition(first,last,pred);
    quickSort(first,mid);
    quickSort(mid,last);
    --mid;
    swap(*mid,*first);
    for(auto itr = first;itr!=last;++itr)
        cout<<(*itr)<<" ";
    cout<<endl;
}

It gives segFault in the partition function. I want to use the library function.

1
  • you know that another C++ library algorithm implements quicksort, right? Commented Jan 8, 2014 at 9:45

2 Answers 2

1

This one uses lambda:

void quick(std::vector<int>::iterator first, std::vector<int>::iterator last)
{
    if (first == last) return;

    auto pivot = *first;
    auto mid = std::partition(first, last, [pivot](int i){return pivot > i;});
    if (mid == last) return;
    quick(first, mid);
    quick(++mid, last);
}
Sign up to request clarification or add additional context in comments.

Comments

1
bool pred(int x) //Return type should be bool.
{
    return x<=p;
}

Inside quicksort

std::vector<int>::iterator mid = partition(first,last,pred);
quickSort(first,mid-1);
quickSort(mid,last);

Rest, check how you are calling it.

1 Comment

Named predicate looks so passe.

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.