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?

  1. A1, 3, 8, 5, 4
  2. B3, 5, 1, 4, 8
  3. 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.
Practice this topic Back to topic

Related calculators

Books on Data Structures and Algorithms Ad

As an Amazon Associate I earn from qualifying purchases.

More Data Structures and Algorithms questions

  1. The array 29, 10, 14, 37, 13 is sorted in ascending order with selection sort, which finds the minimum of the unsorted part and swaps it with the first element of the unsorted part. What is the array after this step has been done twice?
  2. An array of 10 elements is sorted in ascending order with insertion sort. Each element from the second one on is taken out and compared with the elements to its left, starting with its left neighbor, until an element less than or equal to it is found or the front is reached. How many comparisons are made when the array is already in ascending order, and when it is in descending order?
  3. Which sorting algorithm is O(n log n) even in the worst case and sorts with almost no extra memory such as a work array?
  4. The (name, score) records (A, 80), (B, 70), (C, 80), (D, 70) are in this order. If they are sorted by score in ascending order with a stable sort, in what order do the names appear?
  5. Which is a typical case in which quicksort takes O(n²) time?