Search code examples
c++algorithminsertion-sort

Why is my insertion sort algorithm altering numbers in the given array? (C++)


I have a C++n insertion sort function template, and it works fine when I give the function an array of integers, but when I give the function an array of doubles, although the array is indeed sorted afterwards, for some reason it alters the numbers in the sorted array.

The code:

#include <iostream>
#include <stdlib.h>

using namespace std;

template <typename T>
void insertionSort(T ary[10], int size)
{   
    // Printing unsorted array
    cout << "Array before sorting: [";
    for (int i = 0; i < size; i++)
    {
        cout << ary[i] << ", ";
    }
    cout << "]" << endl;

    // Beginning of sorting
    int j, t;
    for(int i = 1; i < size; i++)
    {
        for (int i = 0; i < size; i++)
        {
            j = i;

            while(j > 0 && ary[j] < ary[j-1])
            {
                t = ary[j];
                ary[j] = ary[j-1];
                ary[j-1] = t;
                j--;
            }
        }
    }

    // Printing sorted array
    cout << "Array after sorting: [" ;
    for (int i = 0; i < size; i++)
    {
        cout << ary[i] << ", ";
    }
    cout << "]\n" << endl;
}

int main()
{
    cout << "*** INTEGER ARRAY INSERTION SORT ***" << endl;
    int intAry[10] = {0};
    for (int i = 0; i<= 9; i++)
    {
        intAry[i] = rand() % 100;        
    }

    insertionSort(intAry, 10);

    cout << "*** DOUBLE ARRAY INSERTION SORT ***" << endl;
    double dAry[10] = {0};
    for(int i = 0; i<=9; i++)
    {
        dAry[i] = (double)rand() / RAND_MAX * 100;
    }

    insertionSort(dAry, 10);

    return 0;
}


The output:

enter image description here

You can see here that it changes the number in the array of doubles, like 14.1603 to 14.

Thank you for any help!


Solution

  • The problem is, you want to compare the double numbers, but when you're going through the loop, you use the int i and int j variables. Result is incorrect due to incompatible data type. if you covert "double" the "int" data types, your problem will be solved.

    Also you must change your array type to double.