proccess of this boolean operation

hey guys. can you explain to me the proccess of this boolean operation?
thanks in advance ^^

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
bool swapped = false;
    do
    {
        // 1 pass of the bubble sort
        swapped = false;
        for(int o=0; o<4; o++)
        {
            if(R[o] > R[o+1])
            {
                int temp = R[o];
                R[o] = R[o+1];
                R[o+1] = temp;
                swapped = true;
            }
        }
    }
    while(swapped == true);
It looks through an array of five objects. Each time, if the object it's looking at is bigger than the next one along, it swaps those two round in the array.

It repeats this over and over until it didn't find any to swap when it went through the array. This is the sorting operation known as bubble sort.
closed account (o3hC5Di1)
Hi there,

Here goes:

Your code supposedly sorts the values in array R.
The variable "swapped" is used to keep track of the status of the sorting.

Swapped is set to false at the start of every do/while iteration, and set only to true when a modification was made to the array order.

When no modification was made, the value of swapped remains false and the condition while(swapped == true) evaluates to false, therefore ending the loop.

Hope that helps.

All the best,
NwN

Edit: sorry - slow typer here
Last edited on
I would rewrite the code the following way. Let assume that there is an array

int a[N];

then the sort could look as


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
bool sorted;
size_t n = N;

do
{
   sorted = true;
   if ( n > 1 )
   {
      n--;
      for ( size_t i = 0; i < n; i++ )
      {
         if ( a[i+1] < a[i] )
         {
            sorted = false;
            std::swap( a[i+1], a[i] );
         }
      }
   }
} while ( !sorted );
Last edited on
hmm now i see..
but guys, can you show me the proccess of that iteration using do while without using bool operation?
First of all where do you see "bool operation"? And the second, the do-while requires some boolean condition.
Thanks, I needed an idea for how to sort some things in an array. :D ty ty ty ty

Now to get this to work for me :3
Topic archived. No new replies allowed.