Loading...
Loading...
Loading...
Students stand in a line for a group photo. The photographer asks the 1st and 2nd student to exchange places, then the 3rd and 4th, and so on. If the count is odd, the last student stays where they are. Print the new line.
Example 1
Input
6 1 2 3 4 5 6
Output
2 1 4 3 6 5
Pairs (1,2), (3,4) and (5,6) swap.
Example 2
Input
5 10 20 30 40 50
Output
20 10 40 30 50
The last student, 50, has no partner.
Try the problem first. Open one hint at a time.
Step through the array two at a time: i = 0, 2, 4, …
Swap a[i] and a[i + 1] only while i + 1 < n, so an odd last element is left alone.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor