0% found this document useful (0 votes)
9 views42 pages

4 Wk10 Insertion - Sort - Lecture

Uploaded by

eddieldavies
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views42 pages

4 Wk10 Insertion - Sort - Lecture

Uploaded by

eddieldavies
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Insertion Sort

Dr Rob Blair
[email protected] SCI 2.19

1
Objectives
continue with introduction to sorting

understand how to sort by comparison

2
Comparison Sorting

3
Pseudo Code

4
insertion_sort(array):
for i := 2 to n:
j := i
while array[j] < array[j-1] and j>1:
swap(array[j] array[j-1])
j := j - 1

5
insertion_sort(array):
for i := 2 to n:
j := i
while array[j] < array[j-1] and j>1:
swap(array[j] array[j-1])
j := j - 1

6
insertion_sort(array):
for i := 2 to n:
j := i
while array[j] < array[j-1] and j>1:
swap(array[j] array[j-1])
j := j - 1

7
15 9 22 9 4

8
15 9 22 9 4

9
15 9 22 9 4

10
15 9 22 9 4

11
15 9 22 9 4

12
15 9 22 9 4

13
9 15 22 9 4

14
9 15 22 9 4

15
9 15 22 9 4

16
9 15 22 9 4

17
9 15 22 9 4

18
9 15 22 9 4

19
9 15 22 9 4

20
9 15 22 9 4

21
9 15 9 22 4

22
9 15 9 22 4

23
9 9 15 22 4

24
9 9 15 22 4

25
9 9 15 22 4

26
9 9 15 22 4

27
9 9 15 22 4

28
9 9 15 22 4

29
9 9 15 4 22

30
9 9 15 4 22

31
9 9 4 15 22

32
9 9 4 15 22

33
9 4 9 15 22

34
9 4 9 15 22

35
4 9 9 15 22

36
Time Complexity

37
Time Complexity

(n − 1) + (n − 2) + (n − 3) + . . . + 2 + 1

38
Time Complexity
n−1
n × (n − 1)

k=
k=1
2

39
Time Complexity

2
(n )
𝒪
40
what is the worst case and
best case when sorting?

41
insertion sort is used in
Python*

42

You might also like