Sort the Array with Absolute value only and show real value In C++

Viewed 659

Print the absolute sorted array. See the sample output for clarification.

input:  arr = [2, -7, -2, -2, 0]
output: [0, -2, -2, 2, -7]

Now I am using a lambda function as a comparator for STL std::sort but it's not giving correct answer; a help would be appreciated.

Code:

vector<int> absSort(const vector<int>& at)
{
  vector <int> arr = at;
  
  sort(arr.begin(), arr.end(), [&](const int a, const int b){
    if (abs(a) < abs(b)) return -1;
    if (abs(a) > abs(b)) return 1;
    
    if (a < b) return -1;
    if (a > b) return 1;
    return 0;
    
  });
  return arr;
}
3 Answers

Your comparison function is incorrect. It must return a boolean indicating whether a and b are in the correct order.

It should be something like this:

auto compare = [](int a, int b)
{
    int abs_a = abs(a), abs_b = abs(b);
    if (abs_a < abs_b) return true;
    if (abs_b < abs_a) return false;
    return a < b;
};

Note: It's generally not a good idea to use automatic capture-by-reference ([&]) as it's too easy to accidentally introduce side-effects in your lambdas. I removed this in my example, as there's actually no need to capture anything anyway. We could debate style, but as a matter of personal preference, I always make all my captures explicit, whether they are by reference or by value.

If its abs then does it matter is -2 is before 2 in the sort.

#include <algorithm>
#include <functional>
#include <array>
#include <iostream>

int main()
{
    std::array<int, 6> s = { 2, -7, -2, -2, 0, 7 };

    // sort using a custom lambda
    std::sort(s.begin(), s.end(), [](int a, int b)
    {
        if (abs(a) == abs(b))
            return a < b;
        return abs(a) < abs(b);
    });

    for (auto a : s) {
        std::cout << a << " ";
    }
    std::cout << '\n';
    return 0;

}

If you want something easy to do, just Add cossine/2, the result become a little down for negatives, little up for positives and does not inflict the integer part, not good for production thou.

  sort(arr.begin(), arr.end(), [](auto a, auto b){
      return abs(a + cos(a)/2.) < abs(b + cos(b)/2.);
  });

https://godbolt.org/z/7G9n38

Related