9618 Chapter 23
9618 Chapter 23
Standard Algorithms
Linear Search
The following pseudo code describes a typical variant of linear search, where the
result of the search is supposed to be either the location of the list item where the
desired value was found; or an invalid location -1, to indicate that the desired
element does not occur in the list.
upperBound ← 9
lowerBound ← 0
REPEAT
IF item = myList[index]
THEN
found ← TRUE
ENDIF
index ← index + 1
UNTIL (found = TRUE) OR (index > upperBound)
IF found
THEN
OUTPUT "Item found"
ELSE
OUTPUT "Item not found"
ENDIF
For x = 0 to 10
If items(x) = searchItem Then
Console.WriteLine("Found item " & searchItem & " at position " & x)
Next
End If
If x = 10 Then
console.writeline(-1)
End If
This method works for a list in which the items can be stored in any order, but as
the size of the list increases, the average time taken to retrieve an item increases
correspondingly.
Binary Search
A binary search is more efficient if a list is already sorted. The value of the middle
item in the list is first tested to see if it matches the required item, and the half of
the list that does not contain the required item is discarded. Then, the next item of
the list to be tested is the middle item of the half of the list that was kept. This is
repeated until the required item is found or there is nothing left to test.
For example, consider a list of the letters of the alphabet.
Found ← FALSE
First ←1
Last ←Maxitems
Bubble Sort
Bubble sort is a simple sorting algorithm that works by repeatedly stepping through
the list to be sorted, comparing each pair and swapping them if they are in the
wrong order. The pass through the list is repeated until no swaps are needed, which
indicates that the list is sorted.
Step-by-step example
Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest number
to greatest number using bubble sort algorithm. In each step, elements written
in bold are being compared.
First Pass:
(51428) ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and
swaps them since 5 >1
(15428) ( 1 4 5 2 8 ), It then compares the second and third items and
swaps them since 5 > 4
(14528) ( 1 4 2 5 8 ), Swap since 5 > 2
(14258) ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5),
algorithm does not swap them.
The algorithm has reached the end of the list of numbers and the largest number,
8, has bubbled to the top. It now starts again.
Second Pass:
(14258) ( 1 4 2 5 8 ), no swap needed
(14258) ( 1 2 4 5 8 ), Swap since 4 > 2
(12458) ( 1 2 4 5 8 ), no swap needed
(12458) ( 1 2 4 5 8 ), no swap needed
Now, the array is already sorted, but our algorithm does not know if it is completed.
The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass:
(12458) (12458)
(12458) (12458)
(12458) (12458)
(12458) (12458)
Items ← 10
REPEAT
Swaps←TRUE
FOR Pointer← 1 TO Items – 1
IF NameList[Pointer] > NameList[Pointer + 1]
THEN
Swaps← FALSE
Temp ← NameList[Pointer]
NameList[Pointer] ← NameList[Pointer + 1]
NameList[Pointer + 1] ←Temp
ENDIF
ENDFOR
Items ← Items - 1
UNTIL Swaps = TRUE
Insertion Sort
In this method we compare each number in turn with the numbers before it in
the list. We then insert the number into its correct position.
20 47 12 53 32 84 85 96 45 18
Pseudocode Implementation
FOR ThisPointer ← 2 TO 10
Temp ← NameList[ThisPointer]
Pointer ← ThisPointer – 1
WHILE (NameList[Pointer] > Temp) AND (Pointer > 0)
NameList[Pointer + 1] ← NameList[Pointer]
Pointer ← Pointer - 1
ENDWHILE
NameList[Pointer + 1] ← Temp
ENDFOR
When we want to use an abstract data type, we need a set of basic operations:
ADT is the logical picture of the data and the operations to manipulate the
component elements of the data. Data structure is the actual representation of
the data during the implementation and the algorithms to manipulate
the data elements.
The remainder of this chapter describes the following ADTs: stack, queue, linked
list, binary tree, hash table and dictionary. It also demonstrates how they can be
implemented from appropriate built-in types or other ADTs.
Stacks
Figure shows how we can represent a stack when we have added four items in this
order. Note that the slots are shown numbered from the bottom as this is more
intuitive. The TopOfStackPointer will point to the last element pushed onto the
stack. When an element is removed from the stack, the TopOfStackPoi nter will
decrease to point to the element now at the top of the stack.
The algorithm for insertion is
Pseudocode Implementation
PROCEDURE StackInsert
IF stack is full Then
OUTPUT “ Stack is full”
Else
Input Item
TOS ← TOS +1
stack[TOS] ← item
END If
END PROCEDURE
PROCEDURE StackDelete
IF stack is empty Then
OUTPUT “ Stack is empty”
Else
Output ← stack[TOS]
TOS ← TOS - 1
END If
END PROCEDURE
Queue
Figure shows a queue and its head and tail pointers. Remember, a queue is a first-
in-first-out data structure.
PROCEDURE InsertQueue
ELSE
Input ← newitem
Queue[head] ← newitem
Head ← Head + 1
END IF
END PROCEDURE
PROCEDURE DelQueue
ELSE
Output ←Queue[Tail]
Tail ← Tail + 1
END IF
END PROCEDURE
Linked lists
We used an array as a linear list. In a linear list, the list items are stored in
consecutive locations.
Node: an element of a list
Pointer: a variable that stores the address of the node it points to
Null pointer: a pointer that does not point at anything
Start pointer: a variable that stores the address of the first element of a linked list
PROCEDURE InsertNode(NewItem)
End IF
End Procedure
Binary Trees
Nodes are added to an ordered binary tree in a specific way: Start at the root
node as the current node.
Repeat
If the data value is greater than the current node's data value, follow the
right branch.
If the data value is smaller than the current node's data value, follow the
left branch.
Until the current node has no branch to follow.
Add the new node in this position.
For example, if we want to add a new node with data value D to the binary tree in
Figure, we execute the following steps:
1 Start at the root node.
2 D is smaller than F, so turn left.
3 D is greater than C, so turn right.
4 D is smaller than E, so turn left.
5 There is no branch going left from E, so we add D as a left child from E
Type Tree
End Type
INPUT SearchAnimal
IsFound ← FALSE
Current ← RootPtr
REPEAT
IF SearchAnimal = Tree[Current].data
THEN
OUTPUT 'Found'
IsFound ← TRUE
Graphs
In Computer Science a graph is an ADT consisting of vertices (nodes) and edges.
Graphs are used to record relationships between things. A simple graph is shown
in below figure. It represents a small part of the London Underground map.
The vertices labelled A to F are the underground stations and the edges represent
train lines connecting the stations. For example, you can take a train directly from
B to D. To get from B to F, you have to travel via C or E. Two vertices connected by
an edge are known as neighbours. A labelled (weighted) graph has edges with
values representing something. In our example, we can add weights to below figure
to show the time it takes to travel between stations:
Graphs can be directed or undirected as in below figure. Travel times may vary
depending on the direction of travel.
Sometimes one direction may not be available. For example, if the line from B to
D is blocked, this could be represented as shown in below figure.