Download presentation
Presentation is loading. Please wait.
1
CS2420: Lecture 8 Vladimir Kulyukin Computer Science Department Utah State University
2
Outline Sorting Algorithms (Chapter 7)
3
Insertion Sort template void insertionSort(vector & a) { int right, left; T current_card; for(right = 1; right < a.size( ); right++) { left = right; current_card = a[left]; while (left > 0 && current_card < a[left-1] ) { a[left] = a[left-1]; left--; } a[left] = current_card; }
4
Insertion Sort: Asymptotic Analysis The outer for-loop runs from right = 1 to right = N-1, where N = a.size() The inner for-loop runs: –At iteration 1: 1 time –At iteration 2: 2 times –… –At iteration N-1: N-1 times
5
Insert Sort: Asymptotic Analysis
6
Insertion Sort: Asymptotic Analysis
8
Insertion Sort: Average Analysis Let A be an array of distinct elements. If i A[j], then (A[i], A[j]) is an inversion. Let A = [8, 5, 9, 2, 6, 3]. A has 10 inversions: (8, 5), (8, 2), (8, 6), (8, 3), (5, 2), (5, 3), (9, 2), (9, 6), (9, 3), (6, 3).
9
Insertion Sort: Average Analysis One swap operation in the inner for-loop removes exactly one inversion. If there are I inversions, the swap line will be executed I times, i.e., O(I). The outer loop goes through the entire array once. In other words, it spends O(N) amount of time. Thus, the insertion sort runs in O(I) + O(N) = O(I + N).
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.