cs3003-unit1-notes
Insertion into Sorted List
Description
It is assumed that there is a list
A
which has elements which are already sorted.The task at hand is to insert another element (referred to as
key
) into the sorted listA
so that after the insertion, the list must continue to remain sorted.The
key
is made part of the sorted list by increasing the size by 1 and placing it as the last element of the list. Therefore, space complexity isO(1)
.An iteration of
j
is begun fromi-1
all the way to0
The
key
is compared with the last elementA[j-1]
of the sorted list. If the element is greater than the key, it is shifted right to A[j].
If key is greater than the element in the list, insertion happens at the location
j
and the iteration is exitedThe function returns with the list containing
key
and maintaining the sort order.
Algorithm in pseudocode
Example
Assume sorted list ar = [3, 5, 6, 7]
and element to insert is 2
.
During the intermediary steps, the contents of ar
are as shown below. The key
is value 2
and eventually it gets inserted at beginning of the list.
Source Code
Output
Tower of Hanoi
The Tower of Hanoi problem is a popular puzzle that is used to introduce the concept of Recursion. It also helps to demonstrate the power of recursion in how it can present an elegation solution to a problem of medium complexity.
The rules one must follow when solving the tower puzzle are:
Disks must be removed one at a time from the top of one tower and placed onto the top of another tower.
No disk can be larger than any disk below it (i.e., the disks on each tower make a pyramid shape).
In our three-disc example, we had a simple base case of moving a single disc and a recursive case of moving all of the other discs (two in this case), using the third tower temporarily. We could break the recursive case into three steps:
The amazing thing is that this recursive algorithm works not only for three discs, but for any number of discs. We will codify it as a function called hanoi()
that is responsible for moving discs from one tower to another, given a third temporary tower.
In our Towers of Hanoi solution, we recurse on the largest disk to be moved. That is, we will write a recursive function that takes as a parameter the disk that is the largest disk in the tower we want to move. Our function will also take three parameters indicating from which peg the tower should be moved (source), to which peg it should go (dest), and the other peg, which we can use temporarily to make this happen (spare).
Pseudocode 1
Pseudocode 2
Output for 3 disc Hanoi Problem
Python Code
Hanoi Output
Thinking about Recursion
Last updated