© 2020 IJRAR September 2020, Volume 7, Issue 3 www.ijrar.org (
E-ISSN 2348-1269, P- ISSN 2349-5138
)
IJRAR19L2026
International Journal of Research and Analytical Reviews (IJRAR)
www.ijrar.org
115
Fig. 1 Bubble Sort Code
The above code shown in the Fig 1 takes O(n*n) even in the best case. This code can be optimized by introducing an extra
variable swapped.
Example: First Pass:
(55 11 44 22 88) –> (11 55 44 22 88),
The first two elements compared by algorithm,
until swaps 55 > 11.
(11 55 44 22 88) –> (11 44 55 22 88),
Swaps until 55 > 44
(11 44 55 22 88) –> (11 44 22 55 88),
Swaps until 55 > 22
(11 44 22 55 88) –> (11 44 22 55 88),
Second Pass:
(11 44 22 55 88) –> (11 44 22 55 88),
(11 44 22 55 88) –> (11 22 44 55 88),
Swaps until 44 > 22
(11 22 44 55 88) –> (11 22 44 55 88)
Now, the array is sorted but the algorithm wants one whole pass without any swap to verify.
Third Pass:
(11 22 44 55 88) –> (11 22 44 55 88)
(11 22 44 55 88) –> (11 22 44 55 88)
(11 22 44 55 88) –> (11 22 44 55 88)
(11 22 44 55 88) –> (11 22 44 55 88)
Dostları ilə paylaş: