Data Structures and Algorithms

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?

  1. A45 in both cases
  2. B10 and 100
  3. C9 and 45
Show answer and explanation

Answer: C. 9 and 45

If the array is already ascending, each element needs only one comparison with its left neighbor, so the 9 elements take 9 comparisons in total. If it is descending, the element taken out i-th is compared with all i elements to its left, giving 1 + 2 + … + 9 = 45. Insertion sort thus varies greatly with the input, O(n) in the best case and O(n²) in the worst, and it is very fast on nearly sorted data. Shell sort exploits this by first running insertion sort on elements a gap apart, and Timsort also uses insertion sort for short runs.

  • A. Always making 45 comparisons is true of selection sort. For insertion sort the count depends on the input order.
  • B. The element count 10 and 10² = 100 are not the comparison counts.
  • C. Correct. Ascending order takes one comparison per element (9), and descending order takes 1 + 2 + … + 9 = 45.
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. 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?
  2. 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?
  3. Which is a typical case in which quicksort takes O(n²) time?
  4. In merge sort, the two sorted runs 1, 4, 7, 9 and 2, 3, 8, 10 are merged into one by repeatedly comparing their front elements and outputting the smaller. When one run is empty, the rest of the other is output without comparisons. How many comparisons are made?
  5. A binary heap is stored in an array a[0], a[1], a[2], … with the root at a[0], filling each level from left to right starting at the top. Which are the children and the parent of a[4]?