Book 4 · Chapter P4.5
Sorts and searches
B4·5This chapter is in the ebook.
Read it in full on cswithzak.com. Every question has its mark scheme and every program is ready to run. The free practice for each section is below, with the short code the book prints beside it.
For the whole chapter
- Topic pageComputational Thinking and Problem-Solving
B4·5·T - QuizComputational Thinking & Problem-Solving
B4·5·Q1 - LabAlgorithm Lab (sorts, binary search, recursion)
B4·5·X1 - LabData Structures Playground
B4·5·X2 - LabProgramming tasks (stacks, queues, recursion)
B4·5·X3
§19.1 Algorithms · Building ADTs from other ADTs
Short code B4·5·1
- FlashcardsFlashcards §19.1: ADTs in code — stacks, queues, lists, trees, hash tables
B4·5·F1 - FlashcardsFlashcards §19.1: Algorithms & Big O
B4·5·F2 - Past-paper questionsPast-paper questions §19.1 (algorithms)
- Past-paper questionsPast-paper questions §19.1 (building-adts-from-other-adts)
Part A: linear search in code
Short code B4·5·10
def LinearSearch(Tickets, Target):
Index = 0
while Index < len(Tickets):
if Tickets[Index] == Target:
return Index
Index = Index + 1
return -1
Tickets = [47, 12, 85, 30, 61, 9, 74, 28]
print(LinearSearch(Tickets, 61))
print(LinearSearch(Tickets, 47))
print(LinearSearch(Tickets, 50))Output
4 0 -1
def LinearSearch(Tickets, Target):
Index = 0
while Index < len(Tickets):
if Tickets[Index] == Target:
return Index
Index = Index + 1
return -1
Tickets = [47, 12, 85, 30, 61, 9, 74, 28]
print(LinearSearch(Tickets, 61))
print(LinearSearch(Tickets, 47))
print(LinearSearch(Tickets, 50))Output
4 0 -1
Output
0 47 False 1 12 False 2 85 False 3 30 False 4 61 True returns 4
Three jobs for a linear search
Short code B4·5·11
def Contains(Values, Target):
for Index in range(len(Values)):
if Values[Index] == Target:
return True
return False
def CountOf(Values, Target):
Count = 0
for Index in range(len(Values)):
if Values[Index] == Target:
Count = Count + 1
return Count
Rolls = [4, 6, 2, 6, 1, 6, 3]
print(Contains(Rolls, 2), Contains(Rolls, 5))
print(CountOf(Rolls, 6), CountOf(Rolls, 5))Contains stops at the first match; CountOf must look at every element, because any of them could be another match. (All three languages online at B4·5·11.)Output
True False 3 0
def Contains(Values, Target):
for Index in range(len(Values)):
if Values[Index] == Target:
return True
return False
def CountOf(Values, Target):
Count = 0
for Index in range(len(Values)):
if Values[Index] == Target:
Count = Count + 1
return Count
Rolls = [4, 6, 2, 6, 1, 6, 3]
print(Contains(Rolls, 2), Contains(Rolls, 5))
print(CountOf(Rolls, 6), CountOf(Rolls, 5))Contains stops at the first match; CountOf must look at every element, because any of them could be another match.Output
True False 3 0
def LinearSearch(Tickets, Target):
for Index in range(len(Tickets)):
if Tickets[Index] == Target:
return Index
else:
return -1
Tickets = [47, 12, 85, 30, 61, 9, 74, 28]
print(LinearSearch(Tickets, 47))
print(LinearSearch(Tickets, 61))else returns −1 after looking at one element, so 61 is reported missing although it is at index 4.Output
0 -1
def FindFirstAbove(Values, Limit):
for Index in range(len(Values)):
if Values[Index] > Limit:
return Index
return -1
def CountBelow(Values, Limit):
Count = 0
for Index in range(len(Values)):
if Values[Index] < Limit:
Count = Count + 1
return Count
Values = [12, 7, 31, 18, 40]
print(FindFirstAbove(Values, 20), FindFirstAbove(Values, 50))
print(CountBelow(Values, 20))FindFirstAbove and its faded twin CountBelow, in all three languages.Output
2 -1 3
Binary search: what it needs
Short code B4·5·12
def BinarySearch(Values, Target):
Low = 0
High = len(Values) - 1
while Low <= High:
Mid = (Low + High) // 2
if Values[Mid] == Target:
return Mid
elif Values[Mid] < Target:
Low = Mid + 1
else:
High = Mid - 1
return -1
Tickets = [47, 12, 85, 30, 61, 9, 74, 28]
print(BinarySearch(Tickets, 61))Output
-1
Binary search, iterative
Short code B4·5·13
def BinarySearch(IDs, Key):
Low = 0
High = len(IDs) - 1
while Low <= High:
Mid = (Low + High) // 2
if IDs[Mid] == Key:
return Mid
elif IDs[Mid] < Key:
Low = Mid + 1
else:
High = Mid - 1
return -1
IDs = [104, 117, 123, 138, 145, 159, 162, 170,
186, 191, 203, 218, 226, 239, 247]
print(BinarySearch(IDs, 123))
print(BinarySearch(IDs, 200))Low passes High and the function returns −1. (All three languages online at B4·5·13.)Output
2 -1
def BinarySearch(IDs, Key):
Low = 0
High = len(IDs) - 1
while Low <= High:
Mid = (Low + High) // 2
if IDs[Mid] == Key:
return Mid
elif IDs[Mid] < Key:
Low = Mid + 1
else:
High = Mid - 1
return -1
IDs = [104, 117, 123, 138, 145, 159, 162, 170,
186, 191, 203, 218, 226, 239, 247]
print(BinarySearch(IDs, 123))
print(BinarySearch(IDs, 200))Low passes High and the function returns −1.Output
2 -1
Output
123 0 14 7 170 123 0 6 3 138 123 0 2 1 117 123 2 2 2 123 returns 2 200 0 14 7 170 200 8 14 11 218 200 8 10 9 191 200 10 10 10 203 200 10 9 loop ends returns -1
IDs = [104, 117, 123, 138, 145, 159, 162, 170,
186, 191, 203, 218, 226, 239, 247]
Key = 247
Low = 0
High = len(IDs) - 1
Passes = 0
while Low <= High and Passes < 8:
Passes = Passes + 1
Mid = (Low + High) // 2
print(Low, High, Mid)
if IDs[Mid] == Key:
break
elif IDs[Mid] < Key:
Low = Mid # the fault: should be Mid + 1
else:
High = Mid - 1Low = Mid, the pointers stop moving at 13 and 14.Output
0 14 7 7 14 10 10 14 12 12 14 13 13 14 13 13 14 13 13 14 13 13 14 13
def BinarySearch(Data, Key):
Low = 0
High = len(Data) - 1
while Low <= High:
Mid = (Low + High) // 2
if Data[Mid] == Key:
return Mid
elif Data[Mid] < Key:
Low = Mid + 1
else:
High = Mid - 1
return -1
print(BinarySearch([2, 5, 8, 13, 21, 34], 21), BinarySearch([2, 5, 8, 13, 21, 34], 4))
Names = ["Asif", "Bushra", "Danish", "Farah", "Kamran"]
print(BinarySearch(Names, "Farah"), BinarySearch(Names, "Bilal"))Output
4 -1 3 -1
Binary search, recursive
Short code B4·5·14
def BinarySearch(IDs, Key, Low, High):
if Low > High:
return -1
Mid = (Low + High) // 2
if IDs[Mid] == Key:
return Mid
elif IDs[Mid] < Key:
return BinarySearch(IDs, Key, Mid + 1, High)
else:
return BinarySearch(IDs, Key, Low, Mid - 1)
IDs = [104, 117, 123, 138, 145, 159, 162, 170,
186, 191, 203, 218, 226, 239, 247]
print(BinarySearch(IDs, 123, 0, len(IDs) - 1))
print(BinarySearch(IDs, 200, 0, len(IDs) - 1))Low > High is the not-found base case. The first call passes the whole array, 0 to 14. (All three languages online at B4·5·14.)Output
2 -1
def BinarySearch(IDs, Key, Low, High):
if Low > High:
return -1
Mid = (Low + High) // 2
if IDs[Mid] == Key:
return Mid
elif IDs[Mid] < Key:
return BinarySearch(IDs, Key, Mid + 1, High)
else:
return BinarySearch(IDs, Key, Low, Mid - 1)
IDs = [104, 117, 123, 138, 145, 159, 162, 170,
186, 191, 203, 218, 226, 239, 247]
print(BinarySearch(IDs, 123, 0, len(IDs) - 1))
print(BinarySearch(IDs, 200, 0, len(IDs) - 1))Low > High is the not-found base case. The first call passes the whole array: 0 to 14.Output
2 -1
def BinarySearch(IDs, Key, Low, High):
if Low > High:
return -1
Mid = (Low + High) // 2
if IDs[Mid] == Key:
return Mid
elif IDs[Mid] < Key:
BinarySearch(IDs, Key, Mid + 1, High)
else:
BinarySearch(IDs, Key, Low, Mid - 1)
IDs = [104, 117, 123, 138, 145, 159, 162, 170,
186, 191, 203, 218, 226, 239, 247]
print(BinarySearch(IDs, 170, 0, 14))
print(BinarySearch(IDs, 123, 0, 14))return in front of the recursive calls, the answer found three calls down is thrown away and Python's function ends with nothing: None.Output
7 None
How search time grows
Short code B4·5·15
Output
items linear binary 10 10 4 100 100 7 1000 1000 10 10000 10000 14
def LinearCount(Values, Target):
Count = 0
for Index in range(len(Values)):
Count = Count + 1
if Values[Index] == Target:
return Count
return Count
def BinaryCount(Values, Target):
Count = 0
Low = 0
High = len(Values) - 1
while Low <= High:
Mid = (Low + High) // 2
Count = Count + 1
if Values[Mid] == Target:
return Count
elif Values[Mid] < Target:
Low = Mid + 1
else:
High = Mid - 1
return Count
print("items linear binary")
Size = 10
while Size <= 10000:
Values = []
for Number in range(1, Size + 1):
Values.append(Number)
print(Size, LinearCount(Values, Size + 1), BinaryCount(Values, Size + 1))
Size = Size * 10Output
items linear binary 10 10 4 100 100 7 1000 1000 10 10000 10000 14
Part B: bubble sort in code
Short code B4·5·16
def Show(Values):
Line = ""
for Index in range(len(Values)):
Line = Line + str(Values[Index]) + " "
print(Line)
def BubbleSort(Stock):
for Pass in range(1, len(Stock)):
for Index in range(len(Stock) - Pass):
if Stock[Index] > Stock[Index + 1]:
Temp = Stock[Index]
Stock[Index] = Stock[Index + 1]
Stock[Index + 1] = Temp
Show(Stock)
Stock = [34, 19, 52, 8, 27, 41]
BubbleSort(Stock)Show prints the array after every pass. (All three languages online at B4·5·16.)Output
19 34 8 27 41 52 19 8 27 34 41 52 8 19 27 34 41 52 8 19 27 34 41 52 8 19 27 34 41 52
def Show(Values):
Line = ""
for Index in range(len(Values)):
Line = Line + str(Values[Index]) + " "
print(Line)
def BubbleSort(Stock):
for Pass in range(1, len(Stock)):
for Index in range(len(Stock) - Pass):
if Stock[Index] > Stock[Index + 1]:
Temp = Stock[Index]
Stock[Index] = Stock[Index + 1]
Stock[Index + 1] = Temp
Show(Stock)
Stock = [34, 19, 52, 8, 27, 41]
BubbleSort(Stock)Show prints the array after every pass.Output
19 34 8 27 41 52 19 8 27 34 41 52 8 19 27 34 41 52 8 19 27 34 41 52 8 19 27 34 41 52
Stock = [34, 19, 52, 8, 27, 41]
try:
for Index in range(len(Stock)):
if Stock[Index] > Stock[Index + 1]:
Temp = Stock[Index]
Stock[Index] = Stock[Index + 1]
Stock[Index + 1] = Temp
except IndexError as Error:
print("Stopped at index", Index, "-", Error)Stock[Index + 1] asks for index 6 of a six-element list.Output
Stopped at index 5 - list index out of range
The efficient bubble sort: a swap flag
Short code B4·5·17
def Show(Values):
Line = ""
for Index in range(len(Values)):
Line = Line + str(Values[Index]) + " "
print(Line)
def BubbleSort(Stock):
Top = len(Stock) - 1
while True:
Swapped = False
for Index in range(Top):
if Stock[Index] > Stock[Index + 1]:
Temp = Stock[Index]
Stock[Index] = Stock[Index + 1]
Stock[Index + 1] = Temp
Swapped = True
Show(Stock)
Top = Top - 1
if Swapped == False or Top == 0:
break
Stock = [34, 19, 52, 8, 27, 41]
BubbleSort(Stock)Top shrinks by one each pass, and a pass with no swap ends the sort. (All three languages online at B4·5·17.)Output
19 34 8 27 41 52 19 8 27 34 41 52 8 19 27 34 41 52 8 19 27 34 41 52
def Show(Values):
Line = ""
for Index in range(len(Values)):
Line = Line + str(Values[Index]) + " "
print(Line)
def BubbleSort(Stock):
Top = len(Stock) - 1
while True:
Swapped = False
for Index in range(Top):
if Stock[Index] > Stock[Index + 1]:
Temp = Stock[Index]
Stock[Index] = Stock[Index + 1]
Stock[Index + 1] = Temp
Swapped = True
Show(Stock)
Top = Top - 1
if Swapped == False or Top == 0:
break
Stock = [34, 19, 52, 8, 27, 41]
BubbleSort(Stock)Top shrinks by one each pass, and a pass with no swap ends the sort. On the six stock levels it stops after four passes.Output
19 34 8 27 41 52 19 8 27 34 41 52 8 19 27 34 41 52 8 19 27 34 41 52
Output
1 5 5 4 True 2 4 4 2 True 3 3 3 1 True 4 2 2 0 False
def PassesRight(Values):
Top = len(Values) - 1
Passes = 0
while True:
Swapped = False
Passes = Passes + 1
for Index in range(Top):
if Values[Index] > Values[Index + 1]:
Temp = Values[Index]
Values[Index] = Values[Index + 1]
Values[Index + 1] = Temp
Swapped = True
Top = Top - 1
if Swapped == False or Top == 0:
break
return Passes
def PassesWrong(Values):
Top = len(Values) - 1
Passes = 0
Swapped = False # the fault: set once, never reset
while True:
Passes = Passes + 1
for Index in range(Top):
if Values[Index] > Values[Index + 1]:
Temp = Values[Index]
Values[Index] = Values[Index + 1]
Values[Index + 1] = Temp
Swapped = True
Top = Top - 1
if Swapped == False or Top == 0:
break
return Passes
print("right:", PassesRight([8, 19, 27, 41, 34, 52]), "passes")
print("wrong:", PassesWrong([8, 19, 27, 41, 34, 52]), "passes")Swapped stops the sort after two passes. Set to FALSE once before the loop, it stays TRUE after the first swap, so all five passes run.Output
right: 2 passes wrong: 5 passes
def BubbleSort(Data, Descending):
Top = len(Data) - 1
while True:
Swapped = False
for Index in range(Top):
if Descending == True:
OutOfOrder = Data[Index] < Data[Index + 1]
else:
OutOfOrder = Data[Index] > Data[Index + 1]
if OutOfOrder == True:
Temp = Data[Index]
Data[Index] = Data[Index + 1]
Data[Index + 1] = Temp
Swapped = True
Top = Top - 1
if Swapped == False or Top == 0:
break
Data = [15, 4, 23, 8, 16, 42]
BubbleSort(Data, False)
print(Data)
BubbleSort(Data, True)
print(Data)Output
[4, 8, 15, 16, 23, 42] [42, 23, 16, 15, 8, 4]
Insertion sort in code
Short code B4·5·18
def Show(Values):
Line = ""
for Index in range(len(Values)):
Line = Line + str(Values[Index]) + " "
print(Line)
def InsertionSort(Stock):
for Index in range(1, len(Stock)):
Item = Stock[Index]
Position = Index - 1
Moving = True
while Position >= 0 and Moving == True:
if Stock[Position] > Item:
Stock[Position + 1] = Stock[Position]
Position = Position - 1
else:
Moving = False
Stock[Position + 1] = Item
Show(Stock)
Stock = [34, 19, 52, 8, 27, 41]
InsertionSort(Stock)Item is lifted out, larger values shift one place right, and Item is written once into the gap. (All three languages online at B4·5·18.)Output
19 34 52 8 27 41 19 34 52 8 27 41 8 19 34 52 27 41 8 19 27 34 52 41 8 19 27 34 41 52
def Show(Values):
Line = ""
for Index in range(len(Values)):
Line = Line + str(Values[Index]) + " "
print(Line)
def InsertionSort(Stock):
for Index in range(1, len(Stock)):
Item = Stock[Index]
Position = Index - 1
Moving = True
while Position >= 0 and Moving == True:
if Stock[Position] > Item:
Stock[Position + 1] = Stock[Position]
Position = Position - 1
else:
Moving = False
Stock[Position + 1] = Item
Show(Stock)
Stock = [34, 19, 52, 8, 27, 41]
InsertionSort(Stock)Item is lifted out, larger values shift one place right, and Item is written once into the gap. Show prints the array after each item is inserted.Output
19 34 52 8 27 41 19 34 52 8 27 41 8 19 34 52 27 41 8 19 27 34 52 41 8 19 27 34 41 52
Module Program
Sub Sort(Stock() As Integer, Careful As Boolean)
For Index As Integer = 1 To Stock.Length - 1
Dim Item As Integer = Stock(Index)
Dim Position As Integer = Index - 1
If Careful Then
While Position >= 0 AndAlso Stock(Position) > Item
Stock(Position + 1) = Stock(Position)
Position = Position - 1
End While
Else
While Position >= 0 And Stock(Position) > Item
Stock(Position + 1) = Stock(Position)
Position = Position - 1
End While
End If
Stock(Position + 1) = Item
Next
End Sub
Sub Main()
Dim First() As Integer = {34, 19, 52, 8}
Try
Sort(First, False)
Console.WriteLine("And: sorted")
Catch Problem As Exception
Console.WriteLine("And: " & Problem.GetType().Name)
End Try
Dim Second() As Integer = {34, 19, 52, 8}
Sort(Second, True)
Console.WriteLine("AndAlso: " & Second(0) & " " & Second(1) & " " & Second(2) & " " & Second(3))
End Sub
End ModuleAnd, both tests are worked out even when Position is −1, so Stock(-1) is read and the program stops; AndAlso skips the second test and the sort finishes.Output
And: IndexOutOfRangeException AndAlso: 8 19 34 52
Output
start 2 [19, 34, 52, 8, 27, 41] shift 1 [19, 34, 52, 52, 27, 41] shift 0 [19, 34, 34, 52, 27, 41] shift -1 [19, 19, 34, 52, 27, 41] place -1 [8, 19, 34, 52, 27, 41]
def InsertionSort(Data):
for Index in range(1, len(Data)):
Item = Data[Index]
Position = Index - 1
while Position >= 0 and Data[Position] > Item:
Data[Position + 1] = Data[Position]
Position = Position - 1
Data[Position + 1] = Item
Data = [29, 3, 17, 3, 41, 8]
InsertionSort(Data)
print(Data)and, AndAlso, &&), in all three languages.Output
[3, 3, 8, 17, 29, 41]
Descending order and sorting text
Short code B4·5·19
def SortNames(Names, IgnoreCase):
for Index in range(1, len(Names)):
Item = Names[Index]
Position = Index - 1
Moving = True
while Position >= 0 and Moving == True:
if IgnoreCase == True:
Later = Names[Position].upper() > Item.upper()
else:
Later = Names[Position] > Item
if Later == True:
Names[Position + 1] = Names[Position]
Position = Position - 1
else:
Moving = False
Names[Position + 1] = Item
Names = ["omar", "Bilal", "zara", "aisha", "Hamza"]
SortNames(Names, False)
print(Names)
SortNames(Names, True)
print(Names)Output
['Bilal', 'Hamza', 'aisha', 'omar', 'zara'] ['aisha', 'Bilal', 'Hamza', 'omar', 'zara']
def SortNames(Names, IgnoreCase):
for Index in range(1, len(Names)):
Item = Names[Index]
Position = Index - 1
Moving = True
while Position >= 0 and Moving == True:
if IgnoreCase == True:
Later = Names[Position].upper() > Item.upper()
else:
Later = Names[Position] > Item
if Later == True:
Names[Position + 1] = Names[Position]
Position = Position - 1
else:
Moving = False
Names[Position + 1] = Item
Names = ["omar", "Bilal", "zara", "aisha", "Hamza"]
SortNames(Names, False)
print(" ".join(Names))
SortNames(Names, True)
print(" ".join(Names))compareTo, which gives a number below, equal to or above 0.Output
Bilal Hamza aisha omar zara aisha Bilal Hamza omar zara
Sorting records by a field
Short code B4·5·20
class Team:
def __init__(self, Name, Points):
self.Name = Name # STRING
self.Points = Points # INTEGER
def SortByPoints(Teams):
for Index in range(1, len(Teams)):
Item = Teams[Index]
Position = Index - 1
Moving = True
while Position >= 0 and Moving == True:
if Teams[Position].Points < Item.Points:
Teams[Position + 1] = Teams[Position]
Position = Position - 1
else:
Moving = False
Teams[Position + 1] = Item
Teams = [Team("Falcons", 12), Team("Hawks", 18), Team("Owls", 9),
Team("Eagles", 18), Team("Kites", 15)]
SortByPoints(Teams)
for Index in range(len(Teams)):
print(Teams[Index].Name, Teams[Index].Points).Points, but the move copies the whole record, so every name stays with its points. < gives descending order. (Python; all three languages online at B4·5·20.)Output
Hawks 18 Eagles 18 Kites 15 Falcons 12 Owls 9
class Team:
def __init__(self, Name, Points):
self.Name = Name # STRING
self.Points = Points # INTEGER
def SortByPoints(Teams):
for Index in range(1, len(Teams)):
Item = Teams[Index]
Position = Index - 1
Moving = True
while Position >= 0 and Moving == True:
if Teams[Position].Points < Item.Points:
Teams[Position + 1] = Teams[Position]
Position = Position - 1
else:
Moving = False
Teams[Position + 1] = Item
Teams = [Team("Falcons", 12), Team("Hawks", 18), Team("Owls", 9),
Team("Eagles", 18), Team("Kites", 15)]
SortByPoints(Teams)
for Index in range(len(Teams)):
print(Teams[Index].Name, Teams[Index].Points)Structure and a Java class, each sorted by Points with the same insertion sort. Hawks and Eagles tie on 18 and keep their starting order.Output
Hawks 18 Eagles 18 Kites 15 Falcons 12 Owls 9
Names = ["Falcons", "Hawks", "Owls", "Eagles", "Kites"]
Points = [12, 18, 9, 18, 15]
Top = len(Points) - 1
while True:
Swapped = False
for Index in range(Top):
if Points[Index] < Points[Index + 1]:
Temp = Points[Index]
Points[Index] = Points[Index + 1]
Points[Index + 1] = Temp
TempName = Names[Index]
Names[Index] = Names[Index + 1]
Names[Index + 1] = TempName
Swapped = True
Top = Top - 1
if Swapped == False or Top == 0:
break
for Index in range(len(Names)):
print(Names[Index], Points[Index])Output
Hawks 18 Eagles 18 Kites 15 Falcons 12 Owls 9
Names = ["Falcons", "Hawks", "Owls", "Eagles", "Kites"]
Points = [12, 18, 9, 18, 15]
for Pass in range(1, len(Points)):
for Index in range(len(Points) - Pass):
if Points[Index] < Points[Index + 1]:
Temp = Points[Index]
Points[Index] = Points[Index + 1]
Points[Index + 1] = Temp
for Index in range(len(Names)):
print(Names[Index], Points[Index])Points is swapped, so the points end up in order but every name stays where it started.Output
Falcons 18 Hawks 18 Owls 15 Eagles 12 Kites 9
class Player:
def __init__(self, Name, Goals):
self.Name = Name # STRING
self.Goals = Goals # INTEGER
def SortByGoals(Players):
for Pass in range(1, len(Players)):
for Index in range(len(Players) - Pass):
if Players[Index].Goals < Players[Index + 1].Goals:
Temp = Players[Index]
Players[Index] = Players[Index + 1]
Players[Index + 1] = Temp
Players = [Player("Rehan", 4), Player("Sana", 9), Player("Tariq", 6)]
SortByGoals(Players)
for Index in range(len(Players)):
print(Players[Index].Name, Players[Index].Goals)Player records sorted by Goals into descending order with the two-loop bubble sort, moving whole records, in all three languages.Output
Sana 9 Tariq 6 Rehan 4
Sort, then search: a whole task
Short code B4·5·21
Output
How many scores (1 to 10)? Out of range. How many scores (1 to 10)? Out of range. How many scores (1 to 10)? Score: Score: Score: Score: Score: 8 17 33 42 60 Score to find: 33 is at index 2
Scores = [0] * 10 # ARRAY[0:9] OF INTEGER
Count = 0 # how many elements are in use
def ReadScores():
global Count
Count = int(input("How many scores (1 to 10)? "))
while Count < 1 or Count > 10:
Count = int(input("Out of range. How many scores (1 to 10)? "))
for Index in range(Count):
Scores[Index] = int(input("Score: "))
def SortScores():
Top = Count - 1
Swapped = True
while Swapped == True and Top > 0:
Swapped = False
for Index in range(Top):
if Scores[Index] > Scores[Index + 1]:
Temp = Scores[Index]
Scores[Index] = Scores[Index + 1]
Scores[Index + 1] = Temp
Swapped = True
Top = Top - 1
def FindScore(Key):
Low = 0
High = Count - 1
while Low <= High:
Mid = (Low + High) // 2
if Scores[Mid] == Key:
return Mid
elif Scores[Mid] < Key:
Low = Mid + 1
else:
High = Mid - 1
return -1
ReadScores()
SortScores()
for Index in range(Count):
print(Scores[Index])
Key = int(input("Score to find: "))
Place = FindScore(Key)
if Place == -1:
print(Key, "is not in the list")
else:
print(Key, "is at index", Place)Scores and Count as globals of the module or class, as Python does.Output
How many scores (1 to 10)? Out of range. How many scores (1 to 10)? Out of range. How many scores (1 to 10)? Score: Score: Score: Score: Score: 8 17 33 42 60 Score to find: 33 is at index 2
Part C: counting comparisons and swaps
Short code B4·5·22
def BubbleCount(Data):
Comparisons = 0
Swaps = 0
Top = len(Data) - 1
while True:
Swapped = False
for Index in range(Top):
Comparisons = Comparisons + 1
if Data[Index] > Data[Index + 1]:
Temp = Data[Index]
Data[Index] = Data[Index + 1]
Data[Index + 1] = Temp
Swaps = Swaps + 1
Swapped = True
Top = Top - 1
if Swapped == False or Top == 0:
break
return Comparisons, Swaps
print(BubbleCount([34, 19, 52, 8, 27, 41]))Output
(14, 7)
Output · 4 rows
| data | bubble: comparisons swaps | insertion: comparisons shifts |
|---|---|---|
| sorted | 7 0 | 7 0 |
| one pair swapped | 13 1 | 8 1 |
| jumbled | 28 19 | 23 19 |
| reversed | 28 28 | 28 28 |
Comparisons = 0
Moves = 0
def Fill(Order):
Data = [0] * 8
for Index in range(8):
I = Index + 1 # Book 3's position, 1 to 8
if Order == 1:
Data[Index] = I * 10 # already sorted
elif Order == 2:
Data[Index] = I * 10 # sorted, then one pair swapped
if I == 4:
Data[Index] = 50
if I == 5:
Data[Index] = 40
elif Order == 3:
Data[Index] = ((I * 5) % 8) * 10 + 10 # jumbled
else:
Data[Index] = 90 - I * 10 # reversed
return Data
def BubbleSort(Data):
global Comparisons, Moves
Top = len(Data) - 1
while True:
Swapped = False
for Index in range(Top):
Comparisons = Comparisons + 1
if Data[Index] > Data[Index + 1]:
Temp = Data[Index]
Data[Index] = Data[Index + 1]
Data[Index + 1] = Temp
Moves = Moves + 1
Swapped = True
Top = Top - 1
if Swapped == False or Top == 0:
break
def InsertionSort(Data):
global Comparisons, Moves
for Index in range(1, len(Data)):
Item = Data[Index]
Position = Index - 1
Moving = True
while Position >= 0 and Moving == True:
Comparisons = Comparisons + 1
if Data[Position] > Item:
Data[Position + 1] = Data[Position]
Moves = Moves + 1
Position = Position - 1
else:
Moving = False
Data[Position + 1] = Item
Labels = ["sorted", "one pair swapped", "jumbled", "reversed"]
print("data | bubble: comparisons swaps | insertion: comparisons shifts")
for Order in range(1, 5):
Comparisons = 0
Moves = 0
BubbleSort(Fill(Order))
Line = Labels[Order - 1] + " | " + str(Comparisons) + " " + str(Moves)
Comparisons = 0
Moves = 0
InsertionSort(Fill(Order))
print(Line + " | " + str(Comparisons) + " " + str(Moves))Output · 4 rows
| data | bubble: comparisons swaps | insertion: comparisons shifts |
|---|---|---|
| sorted | 7 0 | 7 0 |
| one pair swapped | 13 1 | 8 1 |
| jumbled | 28 19 | 23 19 |
| reversed | 28 28 | 28 28 |
Growth with n: Big O by experiment
Short code B4·5·23
Output · 4 rows
| n | reversed: bubble insertion | sorted: bubble insertion |
|---|---|---|
| 10 | 45 45 | 9 9 |
| 20 | 190 190 | 19 19 |
| 40 | 780 780 | 39 39 |
| 80 | 3160 3160 | 79 79 |
def BubbleCount(Data):
Count = 0
Top = len(Data) - 1
while True:
Swapped = False
for Index in range(Top):
Count = Count + 1
if Data[Index] > Data[Index + 1]:
Temp = Data[Index]
Data[Index] = Data[Index + 1]
Data[Index + 1] = Temp
Swapped = True
Top = Top - 1
if Swapped == False or Top == 0:
break
return Count
def InsertionCount(Data):
Count = 0
for Index in range(1, len(Data)):
Item = Data[Index]
Position = Index - 1
Moving = True
while Position >= 0 and Moving == True:
Count = Count + 1
if Data[Position] > Item:
Data[Position + 1] = Data[Position]
Position = Position - 1
else:
Moving = False
Data[Position + 1] = Item
return Count
print("n | reversed: bubble insertion | sorted: bubble insertion")
N = 10
while N <= 80:
Reversed = []
Sorted = []
for Value in range(N):
Reversed.append(N - Value)
Sorted.append(Value + 1)
Back1 = BubbleCount(Reversed)
Reversed = []
for Value in range(N):
Reversed.append(N - Value)
Back2 = InsertionCount(Reversed)
Up1 = BubbleCount(Sorted)
Up2 = InsertionCount(Sorted)
print(N, "|", Back1, Back2, "|", Up1, Up2)
N = N * 2MakeData).Output · 4 rows
| n | reversed: bubble insertion | sorted: bubble insertion |
|---|---|---|
| 10 | 45 45 | 9 9 |
| 20 | 190 190 | 19 19 |
| 40 | 780 780 | 39 39 |
| 80 | 3160 3160 | 79 79 |
Built-in sorts, test data and command words
Short code B4·5·24
Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.
Past-paper practice
Short code B4·5·90
Practice for this page of the book: the quiz, flashcards and past-paper questions for its section are listed above.
Workbook 4: Sorts and searches
Short code W4·5 · Practical Programming Task Book
The write-in workbook for this chapter has drills, exam-style practice, trace tables, fix-the-mistake and mark-it-yourself pages. Its full mark schemes and an interactive version arrive here with the chapter.
Starter files
Short code W4·5·K
Data files and skeleton code in Python, VB.NET, Java for this chapter's tasks arrive here with the chapter.


