C ++,输出时将NaN移动到数组的末尾

时间:2015-02-19 16:17:20

标签: c++ arrays sorting nan

所以,我已经制作了一个能够对数组进行排序的程序,并且我试图对包含双FP的数组进行排序,包括我输入的2-3个随机数组,pos inf ,neg inf和单个NaN。所以为了这个目的,我希望对NaN进行排序。 所以我的代码有效,但是当我试图对NaN进行排序时,我无法这样做。我想做的是将它排序到最后,或者将它放在排序数组的末尾。无论如何我真的可以这样做吗?提前致谢!!!代码如下:

int main()
{
int start_s = clock();
int n, k = 4, j; // k is number of elements
double x = -0.0;
double i = 0;
double swap = 0;//used in the function as a place holder and used for swapping between other variables
double a[100] = { (1/x) + (1/i), 2.3, 1/x *0, 1/i };//array of double elements // 1/i * 0 is NaN
//(1 / i) * 0


for (n = 0; n < (k - 1); n++) // for loop consists of variables and statements in order to arrange contents of array
{
  for (j = 0; j < k - n - 1; j++)
    {
      if (a[j] > a[j + 1])

        {
        swap = a[j];
        a[j] = a[j + 1];
        a[j + 1] = swap;

        }
    }
}

cout << "The list of sorted elements within the array, is: " << endl; /* Output message to user */
for (int i = 0; i < k; i++)// Loop up to number of elements within the array
{
    cout << a[i] << " ";/* Output contents of array */
}
cout << endl; //new line

int stop_s = clock();
cout << "The execution time of this sort, is equal to: " << (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000 << " milliseconds" << endl;



return 0; 

3 个答案:

答案 0 :(得分:3)

因为你还是在C ++领域,为什么不充分利用它。首先,确实移动NaN&#39;然后排序。我已经把噪音&#39;从您的代码生成,它编译并运行(编辑:在gcc-4.4.3)。主要区别在于NaN的开头很容易被忽略,因为你会得到一个指向非NaN开头的指针。

#include <iostream>
#include <algorithm>
#include <math.h>

int main()
{
    int n, k = 4, j; // k is number of elements
    double x = -0.0;
    double i = 0;
    double a[100] = { (1/x) + (1/i), 2.3, 1/x *0, 1/i };//array of double elements // 1/i * 0 is NaN]
    double *ptr; // will point at first non-NaN double

    // divide the list into two parts: NaN's and non-NaN's
    ptr = std::partition(a, a+k, isnan);
    // and sort 'm
    // EDIT: of course, start sorting _after_ the NaNs ...
    std::sort(ptr, a+k);

    cout << "The list of sorted elements within the array, is: " << endl; /* Output message to user */
    for (int i = 0; i < k; i++)// Loop up to number of elements within the array
    {
        cout << a[i] << " ";/* Output contents of array */
    }
    cout << endl; //new line

    return 0;
}

答案 1 :(得分:2)

进行线性扫描,找到NaN,并将它们移到最后 - 通过交换。

然后对其余部分进行排序。

您还可以修复比较器,并在那里检查NaN。

有关实际检查,请参阅:Checking if a double (or float) is NaN in C++

答案 2 :(得分:1)

您可以使用isnan()中的cmath来检查NaN。因此,您只需更改比较线:

if (a[j] > a[j + 1])

为:

if (!std::isnan(a[j + 1]) && std::isnan(a[j]) || (a[j] > a[j + 1]))

只是提醒一下,你需要:

#include <cmath>

位于代码顶部。