0

I am creating a bubble sort program for school. The issue is that when I output the results to the user there are random float 0 values in the array and I don't know why they are there. Thanks in advance for any help.

Code:

#include <iostream>
#include <string>

using namespace std;

float* bubble_sort(float* numbers){
   bool changes;
   float temp;
   while(true){
     changes=false;
     //Loop through the array
     for(int i=0; i<sizeof(numbers); i++){
       //Compare the pair
       if(numbers[i]>numbers[i+1]){
       //Swap if the one on the left is larger
          temp=numbers[i];
          numbers[i]=numbers[i+1];
          numbers[i+1]=temp;
       }
     }
     //If there hasn't been any changes 
     //break
     if(changes==false){break;}
   }
   //Return the numbers
   return numbers;
}

int main(){
  while(true){
    try{
      //Get the amount of numbers in the array
      int amount;
      cout<<"How many numbers are in the array ";
      cin>>amount;
      //Setup the array
      float numbers[amount];
      cout<<endl;

      //Get the numbers and add to the array
      for(int i=0; i<amount; i++){
        cout<<"Enter a number to add to the list ";
        cin>>numbers[i];
      }

  //Bubble sort the numbers
  float* result_numbers=bubble_sort(numbers);

  //Format the resulting array for printing
  string result("[");
  for(int i=0; i<sizeof(numbers); i++){
    result=result+to_string(numbers[i])+", ";
  }
  result.append("]");
  //Output the result
  cout<<"The bubble sorted array is: "<<result<<endl;
  break;
}catch(...){
  //Print an error if they don't enter a number
  cerr<<"You must enter a number"<<endl;
 }
}
return 0;
}

When I then run the code with the numbers: 4, 3, 2, 1. I get the output

The bubble sorted array is: [3.000000, 2.000000, 1.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 4.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, ]

K-D-G
  • 160
  • 1
  • 8

0 Answers0