C++ how to sort the values in an array based on magnitude?

2512 views c++
4

For instance I have an array[3] = {-3, 4, 5, 1, -2} I'm trying to sort it as {1, -2, -3, 4, 5} I tried doing bubble sort with abs value but that didn't work out.

answered question

BTW, why not use std::sort ?

Does that work with dynamic single arrays?

Can you put together a Minimal, Complete, and Verifiable example that demonstrates the issue you had with the bubble sort?

Why is array[3] having 5 values?

@ugandanwarlord It works with std::begin and std::end.

can you show your effort?

how do you think array[3] = {-3, 4, 5, 1, -2} this would work?

2 Answers

10

There are plenty of ways to sort like that, and one of the most easiest, in fact, is to use, the std::sort() function from <algorithm>... (Just remember to set up your compiler for C++11 or above)

std::sort(std::begin(array), std::end(array), [](int const num1, int const num2) -> bool
{
    return abs(num1) <= abs(num2);
});

and #include <algorithm> of course...

posted this
3

This will work fine. DEMO is here

int main()
{    
    int numbers[5] = {-3, 4, 5, -2, 2};

    std::sort(std::begin(numbers),std::end(numbers),[](int l, int r) {
        return (std::abs(l) < std::abs(r))
                 ||((std::abs(l) == std::abs(r)) && (l<r));
    });

    for(const auto i : numbers){
        std::cout << i << " ";
    }

    return 0;
}

posted this

Have an answer?

JD

Please login first before posting an answer.