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

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.

Ruks
answered question

ugandan warlord
commented

Does that work with dynamic single arrays?

Retired Ninja
commented

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

### 2 Answers

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...

Ruks
posted this

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

Hiroki
posted this

## Have an answer?

JD

BTW, why not use

`std::sort`

?