简体   繁体   中英

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

For instance I have an array:

array[5]  = {-3, 4, 5, 1, -2}

I am trying to sort it as {1, -2, -3, 4, 5} .

I tried doing bubble sort with abs value but that did not work.

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 )

Create an advanced_absolute function (As pointed out in comments):

constexpr auto min_abs(int x)
{
    return x < 0 ? signed(unsigned(-1)) - signed(unsigned(x) + 1U) : x;
}

And sort:

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

and include these at the top...

#include <algorithm>
#include <iterator> // This is already included the <iostream> and other headers dependent on this header...

You can use the following code:

#include <stdio.h>
#include <stdlib.h>

#define size 5

void swap(int *xp, int *yp) 
{ 
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}
void bubbleSort(int arr[], int n) 
{ 
   int i, j; 
   for (i = 0; i < n-1; i++)       
       for (j = 0; j < n-i-1; j++)  
           if (abs(arr[j]) > abs(arr[j+1])) 
              swap(&arr[j], &arr[j+1]); 
}

int main()
{
   int array[size] = {-3, 4, 5, 1, -2}; 
   bubbleSort(array, size);
   for (int i=0; i<size; i++)
   {
       printf("%d ", array[i]);
   }
   return 0;
}

It can give you a better understanding of how things would work at fine grain level.

Bubblesort function in C is taken from here

Following ruk's idea, but simplified:

#include <algorithm>
#include <iterator> 
#include <cstdlib> 
// ...
std::sort(std::begin(array), std::end(array), [](int const num1, int const num2)
{
    // Don't call std::abs(INT_MIN), just return the correct value directly.
    if (num1==INT_MIN) return false; // First, because INT_MIN<INT_MIN==false 
    if (num2==INT_MIN) return true;
    // If we get here, neither value is INT_MIN so we can safely call std::abs
    return (std::abs(num1) < std::abs(num2));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM