

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


Page 1 Data Structures and Algorithms • Exam 09
LATEST UPDATE 2026/2027 | PREMIUM ACADEMIC EDITION
Exam 09 of 40 | Unit code: DSA-09 | Questions: 6 | Total marks: 30 | Answer ALL questions
Explain bubble sort, including the optimization that lets it finish early, and state its complexities.
Answer:
Bubble sort repeatedly compares adjacent elements and swaps them if they are out of order; after each pass the largest remaining element is at the end. If a full pass makes no swap, the array is sorted and the algorithm stops early.
Worst and average case O(n^2 ); best case O(n) with the early-exit flag; space O(1); stable.
Show the result of the first pass of bubble sort on [5, 1, 4, 2, 8].
Answer:
Compare 5 and 1: swap → [1, 5, 4, 2, 8]. Compare 5 and 4: swap → [1, 4, 5, 2, 8]. Compare 5 and 2: swap → [1, 4, 2, 5, 8]. Compare 5 and 8: no swap.
After pass 1: [1, 4, 2, 5, 8].
Describe selection sort and state its complexities.
Answer:
Selection sort repeatedly finds the minimum of the unsorted part and swaps it into the next position of the sorted part. It makes n(n − 1)/2 comparisons in every case, so its time is always O(n^2 ), with at most n − 1 swaps and O(1) space. The usual version is not stable.
Describe insertion sort. When is it a good choice?
Answer:
Insertion sort builds a sorted prefix: each new element is compared with the sorted elements on its left and shifted into its correct position. Best case O(n) (already sorted), average and worst case O(n^2 ), space O(1), stable.
It is a good choice for small arrays and for nearly sorted data, and is often used inside hybrid algorithms.
Page 2 Data Structures and Algorithms • Exam 09
What is a stable sorting algorithm? State which of bubble, selection and insertion sort are stable.
Answer:
A sorting algorithm is stable if equal keys keep their original relative order. Bubble sort and insertion sort are stable. The standard swap-based selection sort is not stable, because swapping can move an element past equal keys.
How many comparisons does selection sort make on an array of 10 elements? Explain.
Answer:
It compares the minimum search over 9, 8, …, 1 remaining elements: 9 + 8 + … + 1 = n(n − 1)/ = 10 × 9 / 2 = 45 comparisons, regardless of the input order.
Study answers prepared for revision purposes. Always cross-check against your lecturer’s notes and prescribed textbook.