Bubble Sort In Java
Assume that int arr[]= {10,8,9,5,7,6,3,0,1,-3,-6,-9} is our array.
If we were to sort the array in ascending order, it would appear something like this: {-9,-6,-3, 0, 1,,3,5, 6, 7, 8,,9, 10 };
We will use Bubble Sort of 3 level
Algorithm:
- We do two cycles. The inner loop will carry out the comparison and switching operations, while the outside loop will iterate across the array.
- We exchange the current element with the next if it is smaller than the current element.
Working of Bubble Sort:
If we plot the array it look like this
Now to understand the working properly consider this elements as students with the respective height in units.
Iteration 1:
- Student 1 asks Student 2 in the first repetition, "Am I greater than you?" Yes, he responds, and they switch places.[3,5,4,2,1] is arr.
- Student who is 5 feet tall now asks student who is 4 feet tall. Do I surpass you in any way? He affirms. Thus, they exchange places. [3,4,5,2,1] arr.
- Once more, 5 asks 2, and since 5>2, they switch. [3,4,2,5,1] arr.
- 5>1, therefore they switch places. [3,4,2,1,5] is arr.
- At this point, the array is [3,4,2,1,5]. Likewise, 3 queries 4: Am I greater?No, he replies.Consequently, they don't move places.
- 4>2? yeah, They switch positions.
- The next tallest student reaches its proper position after repeating the same requirement.
The greatest integer is placed at the proper end location in each iteration.
1.Level 1
You can see that we require 132 Iterations for sorting the Array
2.Level 2
We include an outer loop iterator in the for loop condition at this level because, as you can see, the highest integer is positioned at the proper end position after each iteration. As a result, we limit the number of inner loop iterations to prevent unnecessary comparisons.
As you can see, there are now only 66 iterations, which should result in a significant reduction in the amount of time needed provided the search space is large enough.
3.Level 3
In this level we use a flag variable to avoid extra comparison if the array is already sorted .
Output:
Comparing Level 2 and Level 3 Bubble Sort:
Lets see it with comparing level 2 and level 3 bubble sort
We will use int arr2[]= {-9 ,-6 ,-3, 0, 1 ,3 ,5, 6, 7, 8 ,9, 10 }; as the array is already sorted so their is no need for extra computation
So lets check our both level codes
Level 2 Bubble Sort:
You can see that even if no computation is needed it still does 66 iterations for i value ranging from 0 to 11
Level 3 Bubble Sort:
You can see that here only 11 comparison is done and only i=0 is run because the array is sorted Thus the time is reduced to run the program.
Please Let me Know, If you have any doubts.
Please Let me Know, If you have any doubts.