AmbifulWorksheets
Cheat sheet
CBSE · Class 12 · Computer Science

Sorting

Bubble, selection and insertion sort as the textbook codes them, pass by pass, with their swaps, shifts and comparisons, and their time complexity.

Key ideas

Remember

Bubble, pass 15, 1, 4, 2, 8 → 1, 4, 2, 5, 8 (3 swaps)
Selection, pass 15, 1, 4, 2, 8 → 1, 5, 4, 2, 8 (1 and 5 swap places)
Insertion, passes 1 and 25, 1, 4, 2, 8 → 1, 5, 4, 2, 8 → 1, 4, 5, 2, 8
Bubble comparisons, n itemsn(n − 1)/2: 6 items → 15
Total swaps or shiftsthe number of pairs out of order: in 5, 1, 4, 2 the pairs 5 1, 5 4, 5 2, 4 2 give 4
Decreasing orderbubble sort swaps when the left item is the smaller

Watch out

Worked example

Sort 29, 12, 28, 54, 47, 31 into increasing order (a) by selection sort and (b) by insertion sort, writing the list after every pass.

Working: selection: swap the smallest of the rest to the front; insertion: insert the next item into the sorted left part

Answer: (a) 12, 29, 28, 54, 47, 31 → 12, 28, 29, 54, 47, 31 → 12, 28, 29, 54, 47, 31 → 12, 28, 29, 31, 47, 54 → 12, 28, 29, 31, 47, 54; (b) 12, 29, 28, 54, 47, 31 → 12, 28, 29, 54, 47, 31 → 12, 28, 29, 54, 47, 31 → 12, 28, 29, 47, 54, 31 → 12, 28, 29, 31, 47, 54