Difference Between Search & Browse Methods in Odoo 17
8 elementary sorts-bubble
1. Bubble Sort
Compares adjacent array elements
– Exchanges their values if they are out of order
Smaller values bubble up to the top of the array
– Larger values sink to the bottom
7. Bubble Sort (cont.)
Example:
77123542 5 101
Largest value correctly placed
0 1 2 3 4 5
8. Bubble Sort (cont.)
• Notice that only the largest value is correctly
placed
• All other values are still out of order
• So we need to repeat this process
77123542 5 101
Largest value correctly placed
0 1 2 3 4 5
9. Bubble Sort (cont.)
Repeat “Bubble Up” How Many Times?
If we have N elements…
And if each time we bubble an element, we place it in its correct location…
Then we repeat the “bubble up” process N – 1 times.
This guarantees we’ll correctly place all N elements.
11. Bubble Sort (cont.)
What if the array was already sorted?
What if only a few elements were out of place and after a couple of “bubble ups,”
the array was sorted?
We want to be able to detect this and “stop early”!
12. Bubble Sort (cont.)
Using a Boolean “Flag”
We can use a boolean variable to determine if any swapping occurred during the
“bubble up.”
If no swapping occurred, then we know that the collection is already sorted!
This boolean “flag” needs to be reset after each “bubble up.”
13. public static void BubbleSort( int [ ] num )
{
int j;
boolean flag = true; // set flag to true to begin first pass
int temp; //holding variable
while ( flag )
{
flag= false; //set flag to false awaiting a possible swap
for( j=0; j > num.length -1; j++ )
if ( num[ j ] > num[j+1] ) // change to > for ascending sort
{
temp = num[ j ]; //swap elements
num[ j ] = num[ j+1 ];
num[ j+1 ] = temp;
flag = true; //shows a swap occurred
}
}
}
}
14. Bubble Sort (cont.)
Excellent performance in some cases
– But very poor performance in others!
Works best when array is nearly sorted to begin with
Worst case number of comparisons: n2
Worst case number of exchanges: n2
Best case occurs when the array is already sorted:
– n comparisons
– 0 exchanges