Search code examples
c++bubble-sort

How do you do a Bubble Sort for an Array in C++?


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


Solution

  • Some of the errors presented in the code are the following

    1. Swapping the values in a wrong manner. ( as pointed out in the comments of the question)
    2. Letting the value of j be 3 in which case it will pick up garbage value in index 4 when temp = num[j+1] is run.
    3. Only having one 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];
        }