1. University MCA (AI/ML) Semester 2
  2. CAP7004
  3. Unit 3

CAP7004 · Unit 3: Searching and sorting

Bubble, selection and insertion sort

8 practice questions

Key points

  • All three are O(n^2) in the worst case
  • Bubble and insertion are stable and O(n) when already sorted
  • Selection always does n(n-1)/2 comparisons
  • Insertion sort is good for nearly sorted data

Three simple O(n^2) comparison sorts.

SortIdeaBestAverage / WorstExtra spaceStable
BubbleSwap adjacent out-of-order pairs; largest moves to the end each passO(n) with early exitO(n^2)O(1)Yes
SelectionPick the minimum of the unsorted part, swap it to the frontO(n^2)O(n^2)O(1)No
InsertionInsert each item into the sorted prefix by shifting larger items rightO(n)O(n^2)O(1)Yes

Worked traces:

  • Bubble sort on [5, 1, 4, 2, 8]: after one pass [1, 4, 2, 5, 8]; it finishes after 3 passes with 4 swaps in total (the third pass makes no swaps, so the early exit stops).
  • Selection sort on [64, 25, 12, 22, 11]: after one pass [11, 25, 12, 22, 64]; always 10 comparisons for n = 5.
  • Insertion sort on [5, 2, 4, 6, 1, 3] makes 9 shifts. On a reversed list of n items it makes n(n-1)/2 shifts, on a sorted list 0.

Stable means equal keys keep their original order. Insertion sort is excellent for small or nearly sorted input.

Exam pitfall: selection sort does the same number of comparisons even for sorted input; its swaps are at most n - 1.

Try two questions

Question 1 · Tier 1, Recall

Selection sort repeatedly:

  1. Splits the list in halves and merges them
  2. Swaps adjacent items that are out of order
  3. Builds a heap and extracts the maximum
  4. Selects the minimum of the unsorted part and swaps it into place
Show the answer

D. After each pass the next smallest value is fixed in position.

Question 2 · Tier 2, Understand

Bubble sort on [5, 1, 4, 2, 8]: the list after the first pass is:

  1. [5, 1, 4, 2, 8]
  2. [1, 5, 4, 2, 8]
  3. [1, 2, 4, 5, 8]
  4. [1, 4, 2, 5, 8]
Show the answer

D. The largest value among the first four moves right by adjacent swaps only: [1, 4, 2, 5, 8].