Mustafizr
Mustafizr

Reputation: 23

I can't wrap my head around the logic of using for loop 5 times for bubble sort

What is the more efficient way of doing the bubble sort instead of me copying and pasting the for loop 5 times using the code given?

My logic here is to check if array[1] (9) is bigger than array[2] (6), since it is bigger it will swap the elements. But once it reaches the end of the array I have to copy and paste the for loop so the bubble sort algorithm will start over again checking the array.

I did not use variables, rather dynamic allocations because it is easier for me to understand.

#include <iostream>

int main()
{
    int array[] = { 9, 6, 2, 8, 3, 1, 7, 5, 4 };

    int temp;

    for (int i = 0; i < 8; i++)
    {
        if (array[i] > array[i + 1])
        {
            temp = array[i];
            array[i] = array[i + 1];
            array[i + 1] = temp;
        }
    }

    for (int i = 0; i < 8; i++)
    {
        if (array[i] > array[i + 1])
        {
            temp = array[i];
            array[i] = array[i + 1];
            array[i + 1] = temp;
        }
    }

    for (int i = 0; i < 8; i++)
    {
        if (array[i] > array[i + 1])
        {
            temp = array[i];
            array[i] = array[i + 1];
            array[i + 1] = temp;
        }
    }

    for (int i = 0; i < 8; i++)
    {
        if (array[i] > array[i + 1])
        {
            temp = array[i];
            array[i] = array[i + 1];
            array[i + 1] = temp;
        }
    }

    for (int i = 0; i < 8; i++)
    {
        if (array[i] > array[i + 1])
        {
            temp = array[i];
            array[i] = array[i + 1];
            array[i + 1] = temp;
        }
    }

    for (int i = 0; i < 8; i++)
    {
        std::cout << array[i] << std::endl;
    }

}

Upvotes: 0

Views: 74

Answers (1)

cigien
cigien

Reputation: 60238

You seem to already know that you can repeat something by using a loop. If you want to repeat a loop, just put it in a loop:

for (int j = 0; j < 8; j++)
  for (int i = 0; i < 8; i++)
    {
        if (array[i] > array[i + 1])
        {
            temp = array[i];
            array[i] = array[i + 1];
            array[i + 1] = temp;
        }
    }

I'm not clear why you would want to do this just 5 times though, there's nothing special about 5.

Also, note that this is not the most efficient way to write a bubble sort (e.g. you don't need to check elements that have already been bubbled up).

Upvotes: 2

Related Questions