0% found this document useful (0 votes)
545 views18 pages

9618 Chapter 23

The document provides information about computational thinking and problem solving concepts including standard algorithms like linear search and binary search. It describes drawbacks of linear search and the process of binary search. Sorting algorithms like bubble sort and insertion sort are explained with pseudocode examples. Abstract data types (ADTs) like stacks, queues and linked lists are defined. Implementation of stacks and queues using arrays is demonstrated with pseudocode. Linked lists are conceptualized using nodes and pointers.
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)
545 views18 pages

9618 Chapter 23

The document provides information about computational thinking and problem solving concepts including standard algorithms like linear search and binary search. It describes drawbacks of linear search and the process of binary search. Sorting algorithms like bubble sort and insertion sort are explained with pseudocode examples. Abstract data types (ADTs) like stacks, queues and linked lists are defined. Implementation of stacks and queues using arrays is demonstrated with pseudocode. Linked lists are conceptualized using nodes and pointers.
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/ 18

A2 Computer Science 9618 Paper 3 Notes Subject Teacher: Fahim Siddiq 03336581412

Computational Thinking and Problem Solving

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.

DECLARE myList : ARRAY[0:9] OF INTEGER


DECLARE upperBound : INTEGER
DECLARE lowerBound : INTEGER
DECLARE index : INTEGER
DECLARE item : INTEGER
DECLARE found : BOOLEAN

upperBound ← 9
lowerBound ← 0

OUTPUT "Please enter item to be found"


INPUT item
found ← FALSE
index ← lowerBound

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

Dim items() = {"h","g","a","d","w","n","o","q","l","b","c"}


Dim searchItem As string
Console.WriteLine("What are you searching for: ")
searchItem = Console.ReadLine()

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

Drawback of Linear Search

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

WHILE Found= FALSE

Middle ← (First+ Last) DIV 2

IF List [Middle] = Searchitem


THEN
Found ← TRUE

Else IF List [Middle] > Searchitem THEN


Last ← Middle
ELSE
First ← Middle+ 1
ENDIF
ENDWHILE
Sorting Algorithms

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)

Finally, the array is sorted, and the algorithm can terminate.


Pseudocode implementation

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.

Consider the list

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

Abstract Data Types (ADTs)


Abstract Data Type: a collection of data with associated operations

When we want to use an abstract data type, we need a set of basic operations:

• create a new instance of the data structure


• find an element in the data structure
• insert a new element into the data structure
• delete an element from the data structure
• access all elements stored in the data structure in a systematic manner

Difference between ADT and Data Structure

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

1- Check to see if stack is full


2- If the stack is full report an error and stop
3- Increment the stack pointer
4- Insert new data item into cell pointed to by the stack pointer and stop.

The algorithm for deletion is

1- Check to see if the stack is empty


2- If the stack is empty report an error and stop
3- Copy data item in cell pointed to by the stack pointer
4- Decrement the stack pointer

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.

The algorithm for insertion is

1- Check to see the queue is full or not


2- If the queue is full report an error and stop
3- Insert new data item into cell pointed to by the head pointer
4- Increment the head pointer stop

The algorithm for deletion is

1- Check to see if the queue is empty


2- If the queue is empty report error and stop
3- Copy data item in cell pointed to by the tail pointer
4- Increment tail pointer and stop

PROCEDURE InsertQueue

IF Queue is full Then

OUTPUT “Queue is already full”

ELSE

Input ← newitem

Queue[head] ← newitem

Head ← Head + 1

END IF

END PROCEDURE

PROCEDURE DelQueue

IF Queue is Empty Then

OUTPUT “Queue is empty”

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

Conceptual diagram of a linked list.

Conceptual diagram of adding a new node to the end of a linked list

Conceptual diagram of Deleting the first node in a linked list


01 Current ← StartPtr
02 IF Current = 0
03 THEN
04 OUTPUT "Empty List" (or similar message)
05 ELSE
06 IsFound ← FALSE
07 INPUT ThisSurname
08 REPEAT
09 IF SurnameList[Current].Surname = ThisSurname
10 THEN
11 IsFound ← TRUE
12 OUTPUT "Surname found at position ", Current
13 ELSE
14 // move to the next list item
15 Current ← SurnameList[Current].Ptr
16 ENDIF
17 UNTIL IsFound = TRUE OR Current = 0
18 IF IsFound = FALSE
19 THEN
20 OUTPUT "Not Found"
21 ENDIF
22 ENDIF

Create a New Linked List


TYPE ListNode
DECLARE Data : STRING
DECLARE Pointer : INTEGER
ENDTYPE

DECLARE StartPointer : INTEGER


DECLARE FreeListPtr : INTEGER
DECLARE List : ARRAY[0 : 6] OF ListNode

StartPointer ← NullPointer // set start pointer


FreeListPtr ← 0 // set starting position of free list
FOR Index ← 0 TO 5 // link all nodes to make free list
List[Index].Pointer ← Index + 1
NEXT Index
List[6].Pointer ← NullPointer // last node of free list

Add a New Node as a First Node in an Ordered LinkList

PROCEDURE InsertNode(NewItem)

IF StartPointer <> NullPointer


THEN // there is space in the array
// take node from free list and store data item
NewNodePtr ← StartPointer
List[NewNodePtr].Data ← NewItem
StartPointer ← List[FreeListPtr].Pointer

End IF

End Procedure

Add a New Node in the Middle of an Ordered LinkList


PROCEDURE InsertNode(NewItem)

IF startpointer <> null


Then
Current ← Startpointer
Repeat
IF List[current].Data >NewItem
Then
List[Free].Data ← NewItem
previous ← List[Free].pointer
List[Free].pointer ← List[current].pointer
List[current].pointer ← previous
Else
current ← List[Current].Ptr
Until current = -1

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

Declare data: String


Declare leftptr: Integer
Declare rightptr: Integer

End Type

INPUT SearchAnimal
IsFound ← FALSE
Current ← RootPtr

REPEAT
IF SearchAnimal = Tree[Current].data
THEN
OUTPUT 'Found'
IsFound ← TRUE

ELSEIF SearchAnimal > Tree[Current].data


THEN
Current ← rightPtr[Current]
ELSE
Current ← leftPtr[Current]
ENDIF
UNTIL 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.

We can use a graph to plan a journey. If we want to travel from C to D, so we can


either use the route C B A D (11 minutes) or the route C F E D (9 minutes). For the
return journey we can use D B C (7 minutes).

To implement a graph, we can use an adjacency matrix or an adjacency list. An


adjacency matrix stores the relationship between every vertex to all other vertices.
For an unweighted graph, a 1 represents an edge, a 0 no edge. When weights are
to be recorded, the weight replaces the 1. Instead of a 0, we use the infinity symbol
∞.
Big O Notation
It is a mathematical notation used to describe the performance or complexity of an
algorithm in relation to the time taken or the memory used for the task. It is used
to describe the worst-case scenario; for example, how the maximum number of
comparisons required to find a value in a list using a particular search algorithm
increases with the number of values in the list.

Big O Order of Time Complexity


O(1) describes an algorithm that always takes deciding if a number is
the same time to perform the task even or odd

O(N) describes an algorithm where the time to a linear search


perform the task will grow linearly in
direct proportion to N, the number of
items of data the algorithm is using
2
O(N ) describes an algorithm where the time to bubble sort, insertion
perform the task will grow linearly in sort
direct proportion to the square of N, the
number of items of data the algorithm is
using
N
O(2 ) describes an algorithm where the time to calculation of Fibonacci
perform the task doubles every time the numbers using recursion
algorithm uses an extra item of data
O(Log N) describes an algorithm where the time to binary search
perform the task goes up linearly as the
number of items goes up exponentially
O(1) describes an algorithm that always uses any algorithm that just
the same space to perform the task uses variables, for
example d = a + b + c
O(N) describes an algorithm where the space to any algorithm that uses
perform the task will grow linearly in arrays, for example a loop
direct proportion to N, the number of to calculate a running
items of data the algorithm is using total of values input to an
array of N elements

You might also like