Insertion and Bubble Sort (A-Level Compsci)
Insertion and Bubble Sort (A-Level Compsci)
INSERTION SORT
1 Davis_Kazibwe@2023KIS
AS & A LEVEL COMPUTER SCIENCE 9618
INSERTION SORT
1 2 3 4 5
9 3 5 2 4
2 Davis_Kazibwe@2023KIS
AS & A LEVEL COMPUTER SCIENCE 9618
INSERTION SORT
1 2 3 4 5
3 9 5 2 4
3 Davis_Kazibwe@2023KIS
AS & A LEVEL COMPUTER SCIENCE 9618
INSERTION SORT
1 2 3 4 5
3 5 9 2 4
4 Davis_Kazibwe@2023KIS
AS & A LEVEL COMPUTER SCIENCE 9618
INSERTION SORT
1 2 3 4 5
2 3 5 9 4
2 3 4 5 9
5 Davis_Kazibwe@2023KIS
AS & A LEVEL COMPUTER SCIENCE 9618
PSEUDOCODE EXAMPLE
1 2 3 4 5 6 7 8 9 10 Positions
11 12 25 33 52 56 57 59 91 85 Elements
ArraySize = 10
FOR Pointer = 2 TO ArraySize
ValueToSort = CardData[Pointer] Temporary storing
PositionToInsert = Pointer
WHILE ( PositionToInsert > 1 ) AND ( CardData[PositionToInsert – 1 >
ValueToSort )
CardData[ PositionToInsert] = CardData[PositionToInsert – 1]
PositionToInsert = PositionToInsert -1
ENDWHILE Shifting
CardData[PositionToInsert] = ValueToSort
NEXT
Inserting Element
6 Davis_Kazibwe@2023KIS
AS & A LEVEL COMPUTER SCIENCE 9618
DRY RUN
Note: If elements are already sorted, While Loop will be skipped straight to the
array initialization statement outside the while loop
7 Davis_Kazibwe@2023KIS
AS & A LEVEL COMPUTER SCIENCE 9618
DRY RUN
8 Davis_Kazibwe@2023KIS
AS & A LEVEL COMPUTER SCIENCE 9618
BUUBLE SORT
Situation: When a list is almost sorted
Reason: Because it stops as soon as it is sorted
INSERTION SORT
Situation: When there are large numbers of data items
Reason: Because it will perform fewer comparisons
9 Davis_Kazibwe@2023KIS
AS & A LEVEL COMPUTER SCIENCE 9618
INSERTION SORT
10 Davis_Kazibwe@2023KIS
AS & A LEVEL COMPUTER SCIENCE 9618
INSERTION SORT
11 Davis_Kazibwe@2023KIS
AS & A LEVEL COMPUTER SCIENCE 9618
INSERTION SORT
12 Davis_Kazibwe@2023KIS
AS & A LEVEL COMPUTER SCIENCE 9618
BUBBLE SORT
Consider StudentID array containing 100 elements.
Boundary = 99
REPEAT
NoMoreSwaps = TRUE
FOR m = 1 TO Boundary
IF StudentID(m) > StudentID(m+1)
THEN
TempStorage = StudentID(m)
StudentID(m) = StudentID(m+1)
StudentID(m+1) = TempStorage
NoMoreSwaps = FALSE
ENDIF
NEXT
Boundary = Boundary - 1
UNTILL NoMoreSwaps = TRUE
13 Davis_Kazibwe@2023KIS