Search code examples
c++sortingstlabsolute-value

to sort the numbers usig absoluter value using stl c++


I am trying to sort the given array based on absolute value using stl sort function but it is not sorting in the specified order: The code that I wrote:

int fun(int i,int j)
{
    if(abs(i)<abs(j))
        return j;
    else
        return i;
}

int main()
{
    int arr[100000];
    int i,n;
    cin>>n;
    for(i=0;i<n;i++)
        cin>>arr[i];
    sort(arr,arr+n,fun);

    int diff=1000000ll;
    int x=0;
    int y,z;

    for i 0 to n
       cout<<arr[i];
    return 0;
}

Solution

  • bool fun(int i,int j)
    {
       return abs(i)<abs(j);
    }
    

    sort() need some function has return bool type and it accept your int function because it can assume if it return 0 it is false else it is true. You shoudl just give it it is true or not then let sort() fucntion to do its job. For example, if u change your fun fucntion as i show above, then sort() give you output in ascending order in an absolute manner.

    Actualy i advice you, mostly use lambdas for these sort function , actually if you put them in auto vars then you can call them more easily.Like that,

    auto func=[](int i, int j) { return abs(i) < abs(j); };
    std::sort(arr, arr+n, func);
    

    PS(sorry for language, it's not my mother tongue.)