Insertion Sort

0.0(0)
studied byStudied by 0 people
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/5

flashcard set

Earn XP

Description and Tags

more efficient

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

6 Terms

1
New cards

Insertion Sort

  • Take values one by one from input array

  • Insert into sorted array in correct order

2
New cards

In-Place Algorithm

Insert values into a sorted sub-array instead of completely new array

3
New cards

In-Place Algorithm Code

class InsertionSort {
   static void insertionSort (int[] array) {
      for (int i = 1; i < array.length; i++) {
         int j = 1;
         //swap array[j-1] and array[j]
         while (j > 0 && array[j-1] > array[j]) {
            int tmp = array[j-1];
            array[j-1] = array[j];
            array[j] = tm[;
            j--;
         }
      }
   }
}

4
New cards

Correctness Analysis

Invariant (for 1 ≤ i < length): 

  • At the end of phase 𝑖, the first 𝑖 + 1 entries of the array are sorted (i.e., in increasing order)

Correctness:

  • Prove invariant 

  • Invariant for 𝑖 = length − 1 implies that the algorithm is correct

5
New cards

Worst-Case Time Complexity

Operation Counting:

In each phase 𝑖 (for 1 ≤ 𝑖 < length): 

  • At most 𝑖 comparisons 

  • At most O(𝑖) elementary operations

<p>Operation Counting:</p><p><span>In each phase </span><span style="font-family: &quot;Cambria Math&quot;">𝑖</span><span> (for 1 ≤ </span><span style="font-family: &quot;Cambria Math&quot;">𝑖</span><span> &lt; length):&nbsp;</span></p><ul><li><p><span>At most </span><span style="font-family: &quot;Cambria Math&quot;">𝑖</span><span> comparisons&nbsp;</span></p></li><li><p><span>At most O(</span><span style="font-family: &quot;Cambria Math&quot;">𝑖</span><span>) elementary operations</span></p></li></ul><p></p>
6
New cards

Analysis Summary

  • Best case - O(n) - only for an already sorted array (as it never enters while loop)

  • Average case - O(n^2)

  • Worst case - O(n^2)

  • In-place - yes