CIE AS & A Level Computer Science, section 10.2 (Arrays)
Linear search
A linear search checks each element in turn, from the start, until it finds the value or reaches the end.
Found ← FALSE
i ← 1
WHILE i <= 5 AND Found = FALSE
IF List[i] = Target THEN
Found ← TRUE
ELSE
i ← i + 1
ENDIF
ENDWHILE
- It works on unsorted data.
- On average it checks about half the elements, and in the worst case all of them.
Bubble sort
A bubble sort repeatedly compares neighbouring elements and swaps them if they are in the wrong order. Large values "bubble" to the end. It stops when a pass makes no swaps.
n ← 4
REPEAT
Swapped ← FALSE
FOR i ← 1 TO n - 1
IF List[i] > List[i + 1] THEN
Temp ← List[i]
List[i] ← List[i + 1]
List[i + 1] ← Temp
Swapped ← TRUE
ENDIF
NEXT i
n ← n - 1
UNTIL Swapped = FALSE
Trace
Sort :
| Pass | Array after the pass |
|---|---|
| 1 | |
| 2 | |
| 3 | |
| 4 (no swaps, stop) |
Python
def bubble_sort(a):
n = len(a)
swapped = True
while swapped:
swapped = False
for i in range(n - 1):
if a[i] > a[i + 1]:
a[i], a[i + 1] = a[i + 1], a[i]
swapped = True
n -= 1
return a
def linear_search(a, target):
for i, value in enumerate(a, 1):
if value == target:
return i
return -1
print(bubble_sort([5, 3, 8, 1])) # [1, 3, 5, 8]
print(linear_search([4, 9, 2, 7], 2)) # 3
Common mistake: forgetting the temporary variable in a swap: writing List[i] ← List[i+1] then List[i+1] ← List[i] loses a value. Also, a bubble sort needs a final pass with no swaps to know the data is sorted.
Exam tip: when asked to trace, write the array after each pass (or each swap) in a table. In pseudocode, use Temp for the swap and a Swapped flag to stop early.
Check yourself
Does a linear search need the data to be sorted?
No.
After one pass of a bubble sort on , what is the array?
.
Why is a temporary variable used when swapping two elements?
So that the first value is not overwritten before it has been copied.