Zum Inhalt springen

English:Standard searching and sorting algorithms - Computing Year 11

Aus MOOCsWiki Staging
aiMOOC-Siegel aiMOOC

Standard searching and sorting algorithms - Computing Year 11

QR-Code


Introduction

A school library has an unsorted box of catalogue cards and a long list of requests to check. Should it scan the cards each time, or order them once and search by eliminating whole sections? In this Year 11 course you will trace a binary search, build a merge sort and choose an approach for a given dataset. You will check empty, missing and duplicate cases as carefully as successful examples.

Choose the search to fit the precondition

A linear search checks items in sequence until it finds its target or reaches the end. On unsorted IDs 17, 3, 12, 8 it finds 12 on the third check. It needs no ordering. Binary search can discard a section only if the data are sorted using the same comparison as the search. For sorted IDs 3, 8, 12, 17 and target 8, use zero-based indices. Keep a lower index that is included and an upper index that is excluded. Initially the possible range is from index 0 up to but excluding index 4. The middle index is 2, value 12. Since 12 is greater than 8, keep indices 0 and 1. Middle index 1 contains 8 and the search returns 1.

Suppose the target is 9. The first comparison with 12 again narrows the range to indices 0 and 1. The comparison with 8 then removes index 1 and everything smaller. The lower and upper limits are both 2, which means the candidate range is empty. A missing value is a normal outcome. On unsorted IDs 17, 3, 12, 8, the same 8 search can discard indices 2 and 3 on its first comparison. That discards the actual target. Binary search did exactly what its rule said, but its precondition failed.

A tree of lists split into single entries and merged into sorted lists
Read the diagram in two stages: split the list, then combine ordered runs. The next chapter walks through an example.
A section of library shelving containing rows of books with labels
Use the shelf as a model: what ordering would allow you to rule out an entire section? The photograph alone does not establish its ordering scheme.


Merge two runs then repeat

To merge sorted runs, compare the first remaining item from each run and append the smaller item to the output. Compare 2, 8 with 2, 5. The two 2s tie; take the 2 from the left run first. Then take the right-hand 2, then the 5. One run is now empty, so append the 8 that remains. The result is 2, 2, 5, 8. If the left 2 had the tag A and the right 2 tag B, comparing only numeric keys would leave A before B. Keeping the input order of equal keys is called stability. Choosing left first on a tie preserves this order across the merge.

Merge sort starts by viewing a list as two smaller lists. Each half is sorted the same way until it has zero or one item, so it is already ordered. For 8, 3, 4, 1, split into 8, 3 and 4, 1. Merge the singleton pairs into 3, 8 and 1, 4. Merge these outputs to get 1, 3, 4, 8. All occurrences survive, including duplicates. If a proposed output is sorted but has replaced a 3 with a second 4, it is not correct. To verify results, compare both the order and the number of occurrences of every value.

An animation showing bars divided into smaller runs which are then merged into order
Animation of splitting and merging. Compare its final merge with the four-value trace.


Implement the checks

Read the Python code from the definition of each function to its final return. The search accepts a list already ordered in ascending order. The upper boundary is excluded, so the list length is a valid upper boundary value even though it is not a valid index to inspect. When the middle value is too small, advance the lower bound past it. When it is too large, exclude it by moving the upper bound to that index. Returning -1 indicates absence, and with duplicates the function may return any matching index.

def binary_search(values, target):
    lower, upper = 0, len(values)
    while upper > lower:
        middle = (lower + upper) // 2
        if values[middle] == target:
            return middle
        if target > values[middle]:
            lower = middle + 1
        else:
            upper = middle
    return -1

def merge(left, right):
    result = []
    i, j = 0, 0
    while len(left) > i and len(right) > j:
        if left[i] <= right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    result.extend(left[i:])
    result.extend(right[j:])
    return result

def merge_sort(values):
    if len(values) <= 1:
        return values[:]
    middle = len(values) // 2
    return merge(merge_sort(values[:middle]), merge_sort(values[middle:]))

ids = [8, 3, 4, 1, 3]
ordered = merge_sort(ids)
print(ordered)                    # [1, 3, 3, 4, 8]
print(binary_search(ordered, 4))  # 3
print(binary_search(ordered, 5))  # -1

Use a trace table with columns for lower, upper, inspected index and result of the comparison. In the sort, turn the completed left and right lists into two columns and cross out every item as it is appended. This catches a common programming error: forgetting to append the remaining items after the main comparison loop.

Use a decision rule and test it

For one search through four unsorted entries, scanning is usually simpler than first sorting them. When many searches will be made on a stable list, a one-time sort can make binary search useful. For example, a linear search of 1,024 sorted entries can still check all 1,024 when a value is absent. Binary search discards about half the candidate region at each unsuccessful check and needs at most 11 value inspections for 1,024 entries with this implementation. That count excludes sorting. If new items arrive continuously, maintaining order is a real cost. There is no universal threshold at which one approach becomes preferable.

Test the empty input, a one-item case, a missing ID between two existing ones, both ends, an already sorted input and a reverse-ordered input. With repeated IDs, check that matches point to the required value, and that sorting keeps the right number of repetitions. If you must find the first of several matches, the search must be changed to continue looking left after a match. Test that requirement separately.

Harvard’s algorithms lecture contains worked visual traces. Focus on the merge sort section. Pause when two piles are individually sorted and predict which pile supplies the next element.


Interactive Tasks


Quiz: Test Your Knowledge

Which condition justifies eliminating half a collection in a binary search? (The values are ordered by the comparison being used) (!All values have different lengths) (!The target is known to occur exactly once) (!The list has an even number of values)




What can a linear search do without first sorting? (Check an unordered collection for a target) (!Eliminate half a collection using only its midpoint) (!Guarantee the fewest comparisons on every sorted dataset) (!Recover the original order after a sort)




The ordered values are 3, 8, 12, 17. Which indices remain after first inspecting index 2 for target 8? (Zero and one) (!Two and three) (!Zero and three) (!One and two)




With the given implementation what does it mean when lower and upper become equal? (The candidate range contains no indices) (!One candidate remains) (!The original list is unsorted) (!The target occurs twice)




What must happen after one run runs out during a merge? (Append the unused tail of the other run) (!Restart with the same two runs) (!Remove the largest value appended) (!Reorder scores that tied)




To preserve stability on equal keys which item does the merge choose first? (The left item) (!The right item) (!The newer item) (!The last item in the larger run)




Which is the correct merge of 2, 8 with 2, 5? (2, 2, 5, 8) (!2, 5, 8) (!2, 8, 2, 5) (!2, 2, 8, 5)




Which lists need no more splitting in this merge sort? (Empty lists and singletons) (!Only lists with exactly two entries) (!All even-length lists) (!Only the initial list)




Which test most directly detects an accidental loss of a repeated item? (Sort 4, 2, 4 and verify that both copies of 4 remain) (!Search a sorted list for its first entry) (!Sort an already empty list) (!Search for a target larger than the list maximum)




When is a one-time sort followed by binary searches especially plausible? (Many lookups in a stable list) (!One lookup in a tiny unordered list) (!A source that changes order after each comparison) (!A dataset with no consistent comparison rule)





Memory Game

Linear search Inspect values in sequence
Binary search Narrow a sorted candidate range
Merge Combine two ordered runs
Base case Stop splitting at zero or one item
Stability Preserve the order of ties
Precondition Requirement before applying an algorithm





Drag and Drop

Match the situations Possible responses
Move the lower bound The middle value is below the target
Move the upper bound The middle value is above the target
Return a matching index The inspected value equals the target
Append one remaining tail One input run has no values left
Check duplicates Compare how many times each value occurs





Crossword Puzzle

binary Search that narrows an ordered range by halves
linear Search that can check an unordered sequence one item at a time
merge Combine two ordered runs into one
stable Preserving the original order of equal keys
index Number which identifies a position in the list
target Value that a search tries to find





LearningApps

If the search returns no suitable result, use the matching task on this page.


Cloze Text

Complete the text.
A

search can inspect an unordered list. A

search requires a consistent order. It compares the

item with the value sought. If the target is greater, move the

limit past the inspected index. When the candidate range is empty, the value is

. Merge sort stops splitting when a run has at most

item. To preserve the order of ties, take the equal item from the

run first. With one run exhausted, append the remaining

of the other.



Open Tasks


Easy

  1. Explain a precondition: Give a three-value unsorted list and explain why comparing with the middle value does not let you discard a side.
  2. Trace a successful search: Search 2, 4, 7, 9, 12 for 9. Record every inspected index and value.
  3. Merge with a leftover: Merge 1, 7 with 2, 3, 11. Record which item is appended at each step.
  4. Find the base cases: Predict the output of merge sort on an empty list and a list containing the single ID 6. State why the recursion stops.


Standard

  1. Trace a missing value: Search 1, 3, 3, 4, 8 for 5 using the given code. Show the candidate range after each unsuccessful comparison.
  2. Check a proposed algorithm: Someone changes lower = middle + 1 to lower = middle. Choose a small sorted list which shows how the revised loop can fail to finish.
  3. Track ties: Sort records labelled 4A, 2B, 4C, 2D by the leading number. Show the order if the left item is chosen first on ties.
  4. Justify a choice: You need to answer 300 requests from one fixed catalogue of 1,024 IDs. Compare the time spent checking entries with the setup work required.


Advanced

  1. Design equal-key tests: Create labels and scores that make an unstable merge observable. Predict both outputs and identify an assertion that distinguishes them.
  2. Find the first match: Sketch an alteration to the binary search that records a match and continues to the left. Test it with the list 2, 5, 5, 5, 9 and with a missing target.
  3. Compare changing catalogues: Describe the costs of re-sorting after every new ID, keeping data ordered as you insert, and deferring the sort. Choose a strategy for one stated arrival pattern.
  4. Prove the merge check: Explain why taking the lesser of two leading values appends the next smallest untouched value. Include the case when one run is empty and discuss why both conditions matter.


Learning Check

  1. Give a counterexample: Show the first decision that makes binary search miss 8 in the unordered list 17, 3, 12, 8 with the supplied code.
  2. Trace both search outcomes: For 1, 3, 3, 4, 8 trace a search for 4 and a search for 5. Give returned values.
  3. Trace a complete sort: Show the splits and merges for 9, 2, 7, 2. Verify that sorting keeps all the original values.
  4. Detect the tail fault: Someone deletes both extend lines from merge. Give a two-item input split over two runs, and show the missing item.
  5. Explain a stable tie: Suppose the left run holds 2A, 4C and the right run holds 2B, 4D. Use the leading numbers as keys and give the stable output order.
  6. Choose a list strategy: Compare scanning with sorting then binary search for one unsorted list searched once and a stable unsorted list searched a thousand times. Give one caveat.


Worked checks

  1. The first middle index is 2 and its value is 12. Since 8 is smaller, the algorithm retains indices 0 and 1. The actual 8 was at index 3 and was just discarded.
  2. For 4, inspect index 2 holding 3, then index 4 holding 8, then index 3 holding 4. Return 3. For 5, the same inspected values exclude indices up to 3 and from 4 onwards. The empty range leads to -1.
  3. Split into 9, 2 and 7, 2, then into four singletons. The sorted halves are 2, 9 and 2, 7. Their merge is 2, 2, 7, 9. One 7 and 9 and both copies of 2 remain.
  4. Merge the singleton runs 1 and 9. The first comparison appends 1, and without extending the still non-empty right run the output is only 1. The missing value is 9.
  5. The stable output is 2A, 2B, 4C, 4D. At a tie the left item joins the result first, matching the relative order of equal keys in the original list.
  6. A scan is a simple way to answer a single request. Sorting once can support many quicker searches on a stable list. This depends on the list size, cost of sorting and how often its entries subsequently change.


Learning evidence

Submit two traces and a short decision note. The search trace must include a failed lookup, and the merge trace must preserve an equal key and a remaining tail. Describe a practical case in which your selected algorithm fits and a change in the task that would make you reconsider it.

OER and Wikipedia


Linked learning areas


aiMOOC Projects



Schulfach+




aiMOOCs



aiMOOC Projekte









MOOCwiki · Deutsch

Nach dem Lernen ist vor dem Lernen

Entdecke direkt den nächsten Lernkurs. Weitere Inhalte erscheinen, wenn Du weiter nach unten scrollst.

Zur MOOCwiki-Hauptseite

Mediathek

Suche verfeinern

Dein Lernplan bestimmt, was oben steht. Alle anderen Inhalte bleiben erreichbar. Seitenaufrufe beeinflussen die Auswahl nicht.

Inhalte werden geladen ...

Mediathek wird aus dem Wiki geladen ...