簡體   English   中英

C++如何根據大小對數組中的值進行排序?

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

例如我有一個數組:

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

我試圖將其排序為{1, -2, -3, 4, 5}

我嘗試使用 abs 值進行冒泡排序,但沒有奏效。

有很多方法可以進行這樣的排序,事實上,最簡單的一種方法是使用<algorithm>std::sort()函數......(請記住為C+設置編譯器+11 或以上)

創建一個 advanced_absolute 函數(如評論中指出的那樣):

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

並排序:

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

並將這些包括在頂部......

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

您可以使用以下代碼:

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

它可以讓您更好地了解事物在細粒度級別的工作方式。

C中的冒泡排序函數取自here

遵循 ruk 的想法,但簡化了:

#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));
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM