|
Answer» Bubble sort, also known as sinking sort, is a basic sorting algorithm that iterates through a list, COMPARING neighbouring elements and swapping them if they are out of order. The list is sent through again and again until it is SORTED. The comparison sort method is named from the manner that smaller or larger components "bubble" to the top of the list. This SIMPLISTIC method performs badly in real-world situations and is mostly used as a teaching aid. Let us take an example to understand how bubble sort works: Let us assume that the array to be sorted is (50 10 40 20 80). The various passes or rounds of bubble sort are given below: - First Pass:
- (50 10 40 20 80) –> ( 10 50 40 20 80 ), Since 50 > 10, the algorithm compares the first two elements and swaps them.
- ( 10 50 40 20 80 ) –> ( 10 40 50 20 80 ), Since 50 > 40, the algorithm swaps the VALUES at the second and third positions.
- (10 40 50 20 80) –> (10 40 20 50 80), Since 50 > 3, the algorithm swaps the third and fourth elements.
- (10 40 20 50 80) -> ( 10 40 20 50 80 ), The method does not swap the fourth and fifth elements because they are already in order (80 > 50).
- Second Pass:
- ( 10 40 20 50 80 ) –> ( 10 40 20 50 80 ) , Elements at first and second POSITION are in order so now swapping.
- ( 10 40 20 50 80 ) –> ( 10 20 40 50 80 ), Since 40 > 20, the algorithm swaps the values at the second and third positions.
- ( 10 20 40 50 80 ) –> ( 10 20 40 50 80 ), Elements at the third and fourth position are in order so now swapping.
- ( 10 20 40 50 80 ) –> ( 10 20 40 50 80 ), Elements at fourth and fifth position are in order so now swapping.
The array is now sorted, but our algorithm is unsure whether it is complete. To know if the algorithm is sorted, it must complete one complete pass without any swaps. - Third Pass:
- ( 10 20 40 50 80 ) –> ( 10 20 40 50 80 ), Elements at the first and second position are in order so now swapping.
- ( 10 20 40 50 80 ) –> ( 10 20 40 50 80 ), Elements at the second and third position are in order so now swapping.
- ( 10 20 40 50 80 ) –> ( 10 20 40 50 80 ), Elements at the third and fourth position are in order so now swapping.
- ( 10 20 40 50 80 ) –> ( 10 20 40 5 80 ), Elements at the fourth and fifth position are in order so now swapping.
|