Preciseness is still a problem. It turns out I wrote something like. (Assuming non-decreasing order)
Listing 1
1 for j = 2 to N
2 key = A[j]
3 i = j -1
4 while i > 0 and A[i] > key
5 A[i+1] = A[i]
6 A[i] = key
7 i = i -1
There's nothing wrong with this code but this is not strictly insertion sort. At line 6, key is exchanged when shifting of the array to right. This is not necessary because we can do (as in TCRC)
Listing 2
1 for j = 2 to N
2 key = A[j]
3 i = j -1
4 while i > 0 and A[i] > key
5 A[i+1] = A[i]
6 i = i -1
7 A[i]= key
This reduces an extra operation in the inner loop.
I also rewrite the C and perl version of the insertion sort. It is a breeze though it is still easy to make mistakes. This type of exercise is great to be done routinely.
* Got to remind myself to refresh on Python and Java. I hope that everytime I write an algorithm, I can think through in at least these 4 langauges.
33_P
This is my self-study page for the book, "Introduction to Algorithm", or commonly known as CLRS. This is also my diary page of how I struggle and grow in the programming world. I hope this blog can help amateurs or professionals, to improve their skills in programming, learning and living. As of Sep 12, 2011, I finished the "exercise read" of Chapter 2 (20110518) and 3 (20110608) and half of Chapter 4.
Shortcut for chapter specific information
Chapter4
(62)
chapter3
(41)
Chapter2
(22)
chapter6
(10)
chapter12
(9)
chapter15
(8)
chapter13
(7)
chapter7
(7)
Chapter10
(5)
chapter5
(5)
Appendix A
(4)
chapter8
(4)
Chapter19
(3)
Chapter22
(3)
Chapter34
(3)
Chapter35
(3)
chapter11
(3)
chapter16
(3)
chapter18
(3)
Appendix C
(2)
Chapter21
(2)
Chapter25
(2)
Chapter26
(2)
Chapter27
(2)
Chapter28
(2)
Chapter29
(2)
Chapter9
(2)
chapter14
(2)
chapter20
(2)
chapter23
(2)
chapter24
(2)
chapter30
(2)
chapter31
(2)
chapter32
(2)
Appendix D
(1)
Chapter1
(1)
Chapter33
(1)
chapter17
(1)
No comments:
Post a Comment