0

I am using this code for the function overloading using C++ to sort a double and an integer array.

 #include<iostream>
#include<bits/stdc++.h>
using namespace std;

void sort(int arr[],int n)
{
    int i,j,key;
    for(j=1;j<n;j++)
    {
        key=arr[j];
        i=j-1;
        while((i>=0)&&(arr[i]>key))
        {
            arr[i+1]=arr[i];
            i--;
        }
        arr[i+1]=key;
    }
    cout<<"Sorted integer array is \n";
    for(i=0;i<n;i++)
    {
        cout<<arr[i]<<endl;
    }
}

void sort(double arr[],int n)
{

    int i,j,key;
    for(j=1;j<n;j++)
    {
        key=arr[j];
        i=j-1;
        while((i>=0)&&(arr[i]>key))
        {
            arr[i+1]=arr[i];
            i--;
        }
        arr[i+1]=key;
    }
    cout<<"Sorted double array is \n";
    for(i=0;i<n;i++)
    {
        cout<<arr[i]<<endl;
    }
}

int main()
{
    int n;
    cout<<"Enter the size of the array \n";
    cin>>n;
    cout<<"Enter the values for the integer function \n";
    int a[n];
    int i;
    for(i=0;i<n;i++)
    {
        cin>>a[i];
    }
    double b[n];
    cout<<"Enter the values for the double array \n";
    for(i=0;i<n;i++)
    {
        cin>>b[i];
    }
    sort(a,n);
    sort(b,n);
}

In the answer it rounds off the values of the double values except the first entry into the double array. Is there any type casting step which I am missing or any other flaw in the code?

Shubam Bharti
  • 73
  • 1
  • 2
  • 11

1 Answers1

5

You are irrevocably cutting off an floating part of double if you save it to int variable.

int key;
key=arr[j];

Thats why are you getting wrong results.

Declare key as double and it works.


Also VLAs (variable length arrays) are not standart C++.

Here are some other variants

  • std::array
  • std::vector
  • use new & delete
kocica
  • 6,412
  • 2
  • 14
  • 35
  • This fixes the immediate issue, but also take a look at some of the comments about variable length arrays, and why you really shouldn't be using them. – Matt Aug 21 '17 at 10:44
  • I meant it more for OP than you :) – Matt Aug 21 '17 at 10:45
  • _"Also VLAs (variable length arrays) are not standart C++ you shouldn't use them._" I disagree with the last part: it is up to OP to know on what arch their code is going to be compiled and eventually decide whether or not they want to use a GNU extension. – YSC Aug 21 '17 at 10:59
  • I wrote it becouse its obvious that OP is beginner and once he could wonder why that code doesnt work on other machines (which havent GNU extension). But i removed it for sure. – kocica Aug 21 '17 at 11:06
  • 1
    @YSC: Too often if someone is coming to SO to ask a question, they do not know VLAs are nonstandard, and such use is completely unintentional. – AndyG Aug 21 '17 at 11:52
  • @AndyG I guess you both are right in this context. My bad. – YSC Aug 21 '17 at 12:02