Quicksort to sort an array of objects by a specific C ++ member

class Foo
{
    public:
        int num;
        int other;
};

int main()
{
    Foo bar[10].num = {1, 9, 3, 5, 1, 6, 10, 0, 6, 3};

    //quicksort(bar)

    return 0;
}

I want to write a quicksort function that orders the array "bar" using "num" in ascending order. Not quite sure which is the best approach to take since I never wrote quicksort. I looked at some code examples, but I don’t see how to modify them for this case. Inplace sorting by pointing to the first and last elements of the array does not work, as it only sorts the "num" member, not the entire object. Dividing an array of objects into a lower array, the vault and the upper array, and recursive sorting seem promising, but I'm not sure how passing values ​​will work ...

Any help is greatly appreciated. Sorry if this was asked before.

+3
4

( ) . bool. true, , false. std:: sort.

struct compare_Foo_by_num
{
    bool operator() (const Foo & lhs, const Foo & rhs) { return lhs.num < rhs.num; }
};

int main()
{
    Foo bar[10];

    std::sort(bar, bar+10, compare_Foo_by_num());
}
+10

operator<, , std::sort.

#include <algorithm>

class Foo
{
public:
    int num;
    int other;
};

bool operator<(const Foo& x, const Foo& y)
{
    return x.num < y.num;
}

int main()
{
    Foo bar[10] = {{1, 5}, {9, 2}, {3, 0}, {5, 7}, {1, 3}, {6, 4}, {10, 8}, {0, 9}, {6, 2}, {3, 5}};
    std::sort(bar + 0, bar + 10);
}

, Foo, , .

operator< Foo, C ++ std::sort.

+2

If you insist on implementing your own quick sort, I suggest watching this video to help you better visualize the algorithm. Although you have never written quicksort, it may be easier for you to implement it after viewing. http://www.youtube.com/watch?v=vxENKlcs2Tw

0
source

Another alternative is to use std :: sort with a lambda expression:

int main()
{
    Foo bar[10] = {{1,5},{9,2},{3,0},{5,7},{1,3},{6,4},{10,8},{0,9},{6,2},{3,5}};

    std::sort(bar, bar + 10, [](const Foo &x, const Foo &y) {
        return x.num < y.num;
    });
}
0
source

Source: https://habr.com/ru/post/1783118/


All Articles