Data Structures and Algorithms
The array 5, 3, 8, 1, 4 is sorted in ascending order with bubble sort. What is the array after one pass, in which neighboring elements are compared from the front to the end and swapped whenever the left one is larger?
- A1, 3, 8, 5, 4
- B3, 5, 1, 4, 8
- C1, 3, 4, 5, 8
Show answer and explanation
Answer: B. 3, 5, 1, 4, 8
Swapping 5 and 3 gives 3, 5, 8, 1, 4; 5 and 8 stay; swapping 8 and 1 gives 3, 5, 1, 8, 4; and swapping 8 and 4 gives 3, 5, 1, 4, 8. One pass carries the maximum value 8 all the way to the end, fixing its position, and the next pass sorts the remaining four elements in the same way. 1, 3, 8, 5, 4 is the array after one pass of selection sort, which swaps the minimum to the front, and 1, 3, 4, 5, 8 is the fully sorted result.
- A. This is the array after one pass of selection sort, which swaps the minimum value 1 to the front.
- B. Correct. Swapping neighbors carries the maximum value 8 to the end.
- C. This is the final sorted result; one pass does not get this far.