Search code examples
c++algorithmsortingbubble-sort

Why is my sort algorithm changing the array values?


This is a simple bubble sort algorithm, part of my larger program, intended to sort an array of doubles. I previously tried sorting the same values with merge sort but I got the same output. I really fail to notice what I am missing.Can someone please point it out to me Thanks in advance!

#include<iostream>
#include<iomanip>

using namespace std;

int const POINTS = 5;
double dataPoints[POINTS] = { 0.1, 0.5, 0.6, 0.2, 0.8 };

void sort(double dataPoints[])
{
    int i, j, flag = 1;    
    int temp;             
    for (i = 1; (i <= POINTS) && flag; i++)
    {
        flag = 0;
        for (j = 0; j < (POINTS - 1); j++)
        {
            if (dataPoints[j + 1] > dataPoints[j])      
            {
                temp = dataPoints[j];             
                dataPoints[j] = dataPoints[j + 1];
                dataPoints[j + 1] = temp;
                flag = 1;              
            }
        }
    }

}

int main()
{

    sort(dataPoints);

    for (int i = 0; i < POINTS; i++)
    {
        cout << dataPoints[i] << " ";
    }

}
Output:

0.8 0 0 0 0  

Solution

  • You swap double, with temporary of type int.

    Use instead:

    double temp;
    

    or better auto:

    const auto temp = dataPoints[j];             
    dataPoints[j] = dataPoints[j + 1];
    dataPoints[j + 1] = temp;
    

    or even better, use std::swap:

    std::swap(dataPoints[j], dataPoints[j + 1]);
    

    If allowed, you can even use:

    std::sort(std::begin(dataPoints), std::end(dataPoints), std::greater<>{});