Kraffs
Kraffs

Reputation: 533

Quicksort function with vector object C++

I'm trying to convert this function to use a vector object instead of an integer array. The vector object looks like this:

std::vector<Heltal *> htal;

The Heltal class contains a private integer named heltal.

How would I sort the htal vector using the function below?

void Array::Sort(int a[], int first, int last)
{
    int low = first;
    int high = last;
    int x = a[(first+last)/2];
    do {
        while(a[low] < x) {
            low++;
        }
        while(a[high] > x) {
            high--;
        }
        if(low<=high) {
            std::swap(a[low],a[high]);
            low++;
            high--;
        }
    } while(low <= high);
    if(first < high)
        Array::Sort(a,first,high);
    if(low < last)
        Array::Sort(a,low,last);
}

Upvotes: 1

Views: 7015

Answers (1)

wjl
wjl

Reputation: 7765

The correct solution is to ditch your custom sort and use std::sort from <algorithm>. This will pretty much be guaranteed to be faster and more optimal in almost every case. Then you just have:

#include <algorithm>
...
std::vector<Heltal *> htal;
...
// sort by pointer value
std::sort(htal.begin(), htal.end());

If you want to sort by object value rather than pointer value, either use std::vector<Heltal> instead of std::vector<Heltal *> (which is almost certainly what you should be doing anyway), or pass a comparison function to std::sort.

Example using C++11 lambda for this:

std::sort(htal.begin(), htal.end(), [](Heltal *a, Heltal *b) { return *a < *b; }); 

Upvotes: 5

Related Questions