0
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
int main()
{
    int n,i,j;
    cin>>n;
    double arr[n];
    for(i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    for(i=0;i<n;i++)
    {
        for(j=(i+1);j<n;j++)
        {
            if(arr[i]>arr[j])
            {
                swap(arr[i],arr[j]);
            }
        }
    }
    for(i=0;i<n;i++)
    {
        cout<<fixed<<setprecision(0)<<arr[i]<<endl;
    }
}
Input:
6
31415926535897932384626433832795
1
3
10
3
5
Output:
1
3
3
5
10
31415926535897932384626433832795
My Output:
1
3
3
5
10
31415926535897933290036940242944

This question is about big sorting problem of hacker rank. Though the logic is right but the data type is not supporting the value used.The value gets changed though i use double or long double or long long. Please tell me the reason for this in detail about the memory that is used by these two data type. Thank you for the answer.

John
  • 157
  • 8
  • 1
    `double arr[n];` is a Variable Length Array. That is *not* valid in standard C++. You want a `std::vector`. – Jesper Juhl Feb 22 '20 at 19:36
  • 2
    Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – walnut Feb 22 '20 at 19:39

1 Answers1

0

This value 31415926535897932384626433832795 will not fit into any common data type as it requires at least 14 bytes in binary representation. As you only need to sort looks like simpler solution would be to compare your numbers as strings. To do so you may need (depends on data requirement) read all values as strings and compare 2 strings this way:

1 eliminate all leading zeroes (you may not need that depends on data requirement)

2 check leading sign, if sign of 2 strings are different return positive as bigger

3 if both negative return negated comarison of the same strings without sign

4 compare length, if one string longer it is bigger

5 compare strings lexicographically (just s1 < s2 )

If you know that data is always positive you may omit steps 2-3

Note1: Variable Length Array is not legal in C++, though some compilers accept it as extention. You should use std::vector

Note2: you should use std::sort() instead of manually implemented bubble sort.

Slava
  • 43,454
  • 1
  • 47
  • 90