简体   繁体   中英

Counting Comparisons Using Insertion Sort

I am tasked with counting the total comparisons while sorting an array. Given the integer array {8, 2, 1, 4, 3, 5}, I am starting from the second element from the left, comparing it to the first, switching them, then comparing the third element to the previous two, and so on, in order to determine where each element should be located.

I am calculating a total of 15 comparisons, but the correct comparison count is 10. I know that sorting this array by selection sort is 15 comparisons, so how and why does the comparison count differ when using Insertion sort in this example?

Your understanding of how the insertion sort is working is wrong.

Using this pseudo code for an insertion sort:

mark first element as sorted
for each unsorted element
  'extract' the element
  for i = lastSortedIndex to 0
    if currentSortedElement > extractedElement
      move sorted element to the right by 1
    else: insert extracted element

Initial array: [8, 2, 1, 4, 3, 5]

Comparison 1: 2 < 8 Array: [2, 8, 1, 4, 3, 5]

Comparison 2: 1 < 8 Array: [2, 1, 8, 4, 3, 5]

Comparison 3: 1 < 2 Array: [1, 2, 8, 4, 3, 5]

Comparison 4: 4 < 8 Array: [1, 2, 4, 8, 3, 5]

Comparison 5: 4 > 2 Array: [1, 2, 4, 8, 3, 5]

Comparison 6: 3 < 8 Array: [1, 2, 4, 3, 8, 5]

Comparison 7: 3 < 4 Array: [1, 2, 3, 4, 8, 5]

Comparison 8: 3 > 2 Array: [1, 2, 3, 4, 8, 5]

Comparison 9: 5 < 8 Array: [1, 2, 3, 4, 5, 8]

Comparison 10: 5 > 4 Array: [1, 2, 3, 4, 5, 8]

Sorted!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM