Unbound
Unbound

Reputation: 335

How do I use C++ library algorithms partition function to quicksort?

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.

Upvotes: 0

Views: 405

Answers (2)

Ezra
Ezra

Reputation: 1481

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

Upvotes: 1

doptimusprime
doptimusprime

Reputation: 9395

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.

Upvotes: 1

Related Questions