Skip to content
Book 4: Practical Programming

Book 4 · Chapter P4.5

Sorts and searches

§19.1In codeBanker · ≈ 33.1 m · ↘B4·5

This 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.

Open in the ebook

§19.1 Algorithms · Building ADTs from other ADTs

Short code B4·5·1

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))
A linear search in Python. It returns the index of the first match, or −1 once every element has been checked. The three calls search for 61, 47 and 50. (All three languages online at B4·5·10.)

Output

4
0
-1
Run and checked before printing
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))
A linear search in code. It returns the index of the first match, or −1 once every element has been checked. The three calls search for 61, 47 and 50.

Output

4
0
-1
Run and checked before printing

Output

0 47 False
1 12 False
2 85 False
3 30 False
4 61 True
returns 4
Run and checked before printing

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))
Two more jobs for a linear search, in Python. 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
Run and checked before printing
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))
Two more jobs for a linear search. 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
Run and checked before printing
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))
The fault in the exhibit, run. The else returns −1 after looking at one element, so 61 is reported missing although it is at index 4.

Output

0
-1
Run and checked before printing
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))
Check: the worked example FindFirstAbove and its faded twin CountBelow, in all three languages.

Output

2 -1
3
Run and checked before printing

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))
A binary search on the unsorted tickets. 61 is in the array, but the search halves the wrong way and reports −1.

Output

-1
Run and checked before printing

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))
An iterative binary search on the 15 sorted IDs, in Python. 123 is found at index 2; for 200, Low passes High and the function returns −1. (All three languages online at B4·5·13.)

Output

2
-1
Run and checked before printing
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))
An iterative binary search on the 15 sorted IDs. 123 is found at index 2; for 200, Low passes High and the function returns −1.

Output

2
-1
Run and checked before printing

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
Run and checked before printing
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 - 1
The exhibit's fault, run with a guard that stops it after eight passes. Searching for 247 with Low = 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
Run and checked before printing
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"))
Check: the worked example (an integer binary search) and its faded twin (a binary search of sorted names), in all three languages.

Output

4 -1
3 -1
Run and checked before printing

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))
A recursive binary search in Python. Each call searches half of the part it was given; 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
Run and checked before printing
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))
A recursive binary search. Each call searches half of the part it was given; Low > High is the not-found base case. The first call passes the whole array: 0 to 14.

Output

2
-1
Run and checked before printing
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))
The exhibit's fault, run. Without 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
Run and checked before printing

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
Run and checked before printing
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 * 10
Counting the comparisons in the worst case: a value bigger than every element, in sorted arrays of 10, 100, 1000 and 10000 items. The linear count grows with n; the binary count grows by about 3 each time n is ten times bigger.

Output

items linear binary
10 10 4
100 100 7
1000 1000 10
10000 10000 14
Run and checked before printing

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)
A bubble sort with two count-controlled loops, in Python. Pass k stops k places from the end, because the k largest values are already there. 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
Run and checked before printing
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)
A bubble sort with two count-controlled loops. Pass k stops k places from the end, because the k largest values are already there. 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
Run and checked before printing
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)
The exhibit's fault, run. The inner loop goes to the last index, so Stock[Index + 1] asks for index 6 of a six-element list.

Output

Stopped at index 5 - list index out of range
Run and checked before printing

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)
The efficient bubble sort in Python: Book 3's algorithm in code. 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
Run and checked before printing
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)
The efficient bubble sort: Book 3's algorithm in code. 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
Run and checked before printing

Output

1 5 5 4 True
2 4 4 2 True
3 3 3 1 True
4 2 2 0 False
Run and checked before printing
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")
The exhibit's fault, run on six values with one pair out of place. Reset at the start of every pass, 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
Run and checked before printing
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)
Check: the worked example (an efficient bubble sort, ascending) and its faded twin (the same sort, descending), in all three languages.

Output

[4, 8, 15, 16, 23, 42]
[42, 23, 16, 15, 8, 4]
Run and checked before printing

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)
An insertion sort in Python: Book 3's flag-controlled algorithm in code. 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
Run and checked before printing
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)
An insertion sort: Book 3's flag-controlled algorithm in code. 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
Run and checked before printing
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 Module
The exhibit's fault, run in VB.NET. With And, 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
Run and checked before printing

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]
Run and checked before printing
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)
Check: the worked example and its faded twin, the insertion sort with both tests in one condition (and, AndAlso, &&), in all three languages.

Output

[3, 3, 8, 17, 29, 41]
Run and checked before printing

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)
Strings are compared character by character, by character code, and every capital letter comes before every small letter. Comparing upper-case copies puts the names in true alphabetical order. (Python; all three languages online at B4·5·19.)

Output

['Bilal', 'Hamza', 'aisha', 'omar', 'zara']
['aisha', 'Bilal', 'Hamza', 'omar', 'zara']
Run and checked before printing
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))
Sorting names, with and without comparing upper-case copies, in all three languages. Java compares strings with compareTo, which gives a number below, equal to or above 0.

Output

Bilal Hamza aisha omar zara
aisha Bilal Hamza omar zara
Run and checked before printing

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)
Sorting records by one field. The comparison reads .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
Run and checked before printing
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)
The league table in all three languages: a Python class, a VB.NET 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
Run and checked before printing
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])
The same table kept in two parallel arrays. Every swap is made in both arrays, so index 0 still names the team that has the points at index 0.

Output

Hawks 18
Eagles 18
Kites 15
Falcons 12
Owls 9
Run and checked before printing
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])
The exhibit's fault, run. Only 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
Run and checked before printing
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)
A further example for practice: 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
Run and checked before printing

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
Run and checked before printing
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)
The whole task in all three languages, run with the same inputs. VB.NET and Java keep 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
Run and checked before printing

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]))
Where the counters go: one just before every comparison, one with every swap. On the six stock levels the efficient bubble sort makes 5 + 4 + 3 + 2 = 14 comparisons and 4 + 2 + 1 = 7 swaps, as in the Trace-it in Spread 17.

Output

(14, 7)
Run and checked before printing

Output · 4 rows

databubble: comparisons swapsinsertion: comparisons shifts
sorted7 07 0
one pair swapped13 18 1
jumbled28 1923 19
reversed28 2828 28
Run and checked before printing
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))
The counting experiment in all three languages. The comparison counts are the ones Book 3, Chapter 19 printed for the same four lists.

Output · 4 rows

databubble: comparisons swapsinsertion: comparisons shifts
sorted7 07 0
one pair swapped13 18 1
jumbled28 1923 19
reversed28 2828 28
Run and checked before printing

Growth with n: Big O by experiment

Short code B4·5·23

Output · 4 rows

nreversed: bubble insertionsorted: bubble insertion
1045 459 9
20190 19019 19
40780 78039 39
803160 316079 79
Run and checked before printing
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 * 2
The doubling experiment in all three languages (VB.NET and Java build each list with a function MakeData).

Output · 4 rows

nreversed: bubble insertionsorted: bubble insertion
1045 459 9
20190 19019 19
40780 78039 39
803160 316079 79
Run and checked before printing

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.

Ask Z about Sorts and searches
Buy ZAK's books — WhatsApp the books desk: Buy the booksPrint or ebook