☰ Year plan · Communication Technology

Search, sort and learning

Week 5 · Unit 1, Lesson 2 Artificial Intelligence Algorithms (2) · 3 lessons
1

Search and sort: finding and ordering data

ICT Prep 3 Term 1, Unit 1, Lesson 2: pp. 22–30
GoalDescribe search and sort algorithms and predict what a search and a sort program shows.
New words
search algorithm · steps that look for an item in a collection of datasorting algorithm · steps that put items in orderascending · from the smallest to the largest, or from A to Zlist · values kept in square brackets, one after another
Explanation

Computers search and sort all the time. A search algorithm looks for an item: you look through a class list for a name, or along a shelf for a book, and you stop when you find it. The simple program below looks at every number of a list (Week 7 explains lists) and remembers whether it met 10. A sorting algorithm puts items in order, ascending: numbers from small to large, names from A to Z. Python has two ways: sorted(numbers) gives a new sorted list and leaves numbers as it was, but numbers.sort() changes the list itself. You can also sort by hand. Compare neighbours and swap them if the left one is larger; after enough rounds the list is in order.

Python
1numbers = [4, 10, 7]
2found = False
3for n in numbers:
4    if n == 10:
5        found = True
6if found:
7    print("Found")
8else:
9    print("Not found")
Output
Found
Worked examples
Python
1numbers = [4, 10, 7]
2found = False
3for n in numbers:
4    if n == 5:
5        found = True
6if found:
7    print("Found")
8else:
9    print("Not found")
Output
Not found
Search for 5 in the same list. No item equals 5, so found stays False and the program shows Not found. This simple version checks every item before it answers.
ABCDE
1Step1st2nd3rd4th
2start5281
3after round 12518
4after round 22158
5after round 31258
Nour sorts 5, 2, 8, 1 by hand. In each round she compares neighbours and swaps when the left one is larger. After three rounds the list reads 1, 2, 5, 8.
Class activity

Write a list of five names of your own on paper and sort them from A to Z by hand, comparing neighbours. Then search for one name and count how many items you looked at before you found it.

Practice
1
What does the search program of the lesson show for the list [4, 10, 7]?
2
What does sorted([4, 10, 7]) give?
3
What is the difference between sorted(numbers) and numbers.sort()?
4
Sort 9, 3, 6 in ascending order.