CS 162 Intro to Programming II Insertion Sort 1. Assume the initial sequence a[0] a[1] … a[k] is...

7
CS 162 Intro to Programming II Insertion Sort 1

description

What k(0) k(1)

Transcript of CS 162 Intro to Programming II Insertion Sort 1. Assume the initial sequence a[0] a[1] … a[k] is...

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.

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.

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.

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.

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.

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.

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.

7

Complexity of Insertion Sort

Best Case- already in order O(n)

Worst Case- reversed O(n2)

Average Case- O(n2)