I am given a 4 numbers that I have to input them and use bubble sort to sort them from lowest to highest. This is what I have currently now for the bubble sorting:
void bubble_sort()
{
for (int i=0;i<4;i++)
{
if(num[i]>num[i+1])
{
float temp;
temp=num[i+1];
num[i]=num[i+1];
num[i+1]=temp;
}
}
}
When I output the the array with the inputs: 3.72, 3.92, 3.46, and 3.86 I get : 3.72, 3.46, 3.46, 0
Some of the errors presented in the code are the following
j
be 3 in which case it will pick up garbage value in index 4 when temp = num[j+1]
is run.for
loop iterating through the loop only once. Kindly read up on the basics of working and Complexity of bubble sort and how it uses at least two loops from here Now the correct answer will be of the form
void bubble_sort(float num[]) {
for (int i=0;i<4;i++) {
for(int j=0;j<3;j++){
if(num[j]>num[j+1])
{
float temp;
temp=num[j+1];
num[j+1]=num[j];
num[j]=temp;
}
}
}
for(int i=0;i<4;i++)
cout<<num[i];
}