Loading...
Loading...
Sort the heights of children for a school photo using bubble sort. In one pass, walk from left to right and swap every pair of neighbours that is in the wrong order, so the largest unsorted height bubbles to the end.
After each pass, print the array. Stop after a pass that makes no swap, or after n - 1 passes. Finally print the total number of swaps.
Swaps: s.Example 1
Input
5 5 1 4 2 8
Output
1 4 2 5 8 1 2 4 5 8 1 2 4 5 8 Swaps: 4
Pass 3 makes no swap, so the sort stops there.
Example 2
Input
3 1 2 3
Output
1 2 3 Swaps: 0
Already sorted: one pass with no swaps.
Try the problem first. Open one hint at a time.
Pass number pass runs from 1 to n - 1. In it, compare a[j] and a[j + 1] for j from 0 to n - 1 - pass.
Swap only when a[j] > a[j + 1], never when they are equal.
Use a boolean swapped per pass; if it stays false, print and stop.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor