![Page 1: CS 162 Intro to Programming II Insertion Sort 1. Assume the initial sequence a[0] a[1] … a[k] is already sorted k = 0 when the algorithm starts Insert](https://reader036.vdocuments.site/reader036/viewer/2022082723/5a4d1b467f8b9ab0599a3693/html5/thumbnails/1.jpg)
1
CS 162Intro to Programming II
Insertion Sort
![Page 2: CS 162 Intro to Programming II Insertion Sort 1. Assume the initial sequence a[0] a[1] … a[k] is already sorted k = 0 when the algorithm starts Insert](https://reader036.vdocuments.site/reader036/viewer/2022082723/5a4d1b467f8b9ab0599a3693/html5/thumbnails/2.jpg)
2
Insertion Sort
• Assume the initial sequence a[0] a[1] … a[k] is already sorted
• k = 0 when the algorithm starts• Insert the array element at a[k+1] into the
proper location of the initial sequence• Note that the insertion enlarges the initial (i.e.
sorted) sequence
![Page 3: CS 162 Intro to Programming II Insertion Sort 1. Assume the initial sequence a[0] a[1] … a[k] is already sorted k = 0 when the algorithm starts Insert](https://reader036.vdocuments.site/reader036/viewer/2022082723/5a4d1b467f8b9ab0599a3693/html5/thumbnails/3.jpg)
3
What4421581623 k(0)
44215823
k(1)
16
4421582316
![Page 4: CS 162 Intro to Programming II Insertion Sort 1. Assume the initial sequence a[0] a[1] … a[k] is already sorted k = 0 when the algorithm starts Insert](https://reader036.vdocuments.site/reader036/viewer/2022082723/5a4d1b467f8b9ab0599a3693/html5/thumbnails/4.jpg)
4
What4421581623
4421582316
4421523168
4422316158
4422316158
4223161584
![Page 5: CS 162 Intro to Programming II Insertion Sort 1. Assume the initial sequence a[0] a[1] … a[k] is already sorted k = 0 when the algorithm starts Insert](https://reader036.vdocuments.site/reader036/viewer/2022082723/5a4d1b467f8b9ab0599a3693/html5/thumbnails/5.jpg)
5
Codevoid insertSort(int a[], int size) {
for( int i = 1; i < size; i++ ){int next = a[i];// Find the insertion location// Move all larger elements upint j = i;while( j > 0 && a[j-1] > next) {
a[j] = a[j-1];j--;}
// Insert the elementa[j] = next;
}}
![Page 6: CS 162 Intro to Programming II Insertion Sort 1. Assume the initial sequence a[0] a[1] … a[k] is already sorted k = 0 when the algorithm starts Insert](https://reader036.vdocuments.site/reader036/viewer/2022082723/5a4d1b467f8b9ab0599a3693/html5/thumbnails/6.jpg)
6
Complexity
• for loop runs for (n-1) iterations• On the kth iteration:– We have k elements that are already sorted– Need to insert into these k elements and move up
the elements that are past the insertion point => k+1 elements visited
• Total # of visits is:
![Page 7: CS 162 Intro to Programming II Insertion Sort 1. Assume the initial sequence a[0] a[1] … a[k] is already sorted k = 0 when the algorithm starts Insert](https://reader036.vdocuments.site/reader036/viewer/2022082723/5a4d1b467f8b9ab0599a3693/html5/thumbnails/7.jpg)
7
Complexity of Insertion Sort
Best Case- already in order O(n)
Worst Case- reversed O(n2)
Average Case- O(n2)