Searching and Sorting Algorithms
In questa pagina 12
In questa pagina 6
Sorting data by a criterion (names in alphabetical order, numbers in ascending order) is a very common problem in data processing. Once data is sorted, searches become much more efficient. Searching and sorting are also the standard setting for comparing algorithms that solve the same problem with asymptotic analysisthe study of how the cost of an algorithm grows with the input size n, ignoring constant factors; the notation and the cost model are in Computational ComplexityAlgorithms are analysed to predict performance on unseen inputs and to compare solutions of the same problem, mainly in time (also in space). Experimental analysis times an implementation (time.time(), doubling input sizes, T(n) = an^b with b = log2(T(2n)/T(n))) but measures the implementation, not the algorithm. Theoretical analysis counts basic steps under a cost model and classifies the result with asymptotic notation: O is an upper bound, Omega a lower bound, Theta both (f(n) <= cg(n) for all n >= n0). Rules: sum sequential blocks, take the larger branch of an if for an upper bound (the smaller for a lower bound), sum the iterations of a loop. Worked case: reverse a list with a shifting inner loop is Theta(n^2); writing each element directly in its place is Theta(n), and no faster hardware can compensate for the worse class on large inputs.Computational Complexity →, and several algorithms below are recursive (RecursionA function is recursive when it calls itself; it is correct only if it has at least one base case that needs no recursive call and if every recursive call works on a simpler problem that gets closer to a base case (otherwise Python stops with RecursionError, the limit being 1000 nested calls). Each pending call is a record on the call stack. Types: linear (one call, e.g. factorial), binary (two calls, e.g. sum of a list by halves), tail (the call is the last action, solved with an accumulator and easy to turn into a loop), multiple (fib_bad recomputes the same values and explodes). Typical examples: factorial, Fibonacci, reversing a string, Towers of Hanoi (2^n - 1 moves). Recursion is elegant for naturally recursive problems but usually less efficient than a loop.Recursion →). Some of them are recursive and efficient, but not all recursive algorithms are efficient (see naive Fibonacci in section 10).
The slides write the list as a; the lecture notes pass v and its logical size v_size, to make the analogy with partially filled arrays clear. The code below is the slide version unless stated.
1. Linear search
Linear search (also called sequential searchanother name for linear search) is the simplest strategy to find a value in a list: scan the list from left to right and compare each element with the value. If the value is found it returns the index, if the end is reached without finding it, it returns -1. It does not require sorted data.
# returns the index of value in the list a
# or -1 is value is not in the list
def linear_search(a, value):
for i in range(len(a)):
if a[i] == value:
return i # FOUND
return -1 # NOT FOUNDExample: a = [8, 5, 3, 9, 1], searching 3 scans a[0], a[1], a[2] and returns 2.
If the value appears several times, linear search returns the first occurrence, because it stops as soon as it meets the value. With v = [7, 4, 7, 9, 7], linear_search(v, len(v), 7) returns 0 (lecture-note version with v_size).
Performance
Cost model of the slides: count the accesses (comparisons) to list elements.
- Worst case: the value is absent or in the last position, so all elements are checked: .
- Average case (value present, every position equally likely): finding it at index takes 1 access, at index takes 2, ..., at index takes . Total , so the average is . Hence : linear search is even on average. Half the list is still linear.
- Best case: the value is at index , a single access.
Grafico interattivo: Linear search: comparisons in the worst case (n) and on average (n/2)
2. Binary search
If the list is sorted the position of an element can be found much more efficiently. Binary search compares the target with the element in (about) the centre of the list, at index (start + end) // 2:
- if the target is greater, it can only be to the right of the centre element: continue in the right sub-list;
- if it is less, continue in the left sub-list;
- if equal, it is found.
The same algorithm is applied to the chosen sub-list. If the sub-list becomes empty the element is not present. It is called binary search because the list is split into two parts at each step, and it only works if the list is sorted (the idea also adapts to decreasing order; on an unsorted list discarding half of the elements is not justified).
Worked trace (slides): searching 12 in [5, 9, 11, 12, 17, 21]
| step | interval (start, end) | mid = (start+end)//2 | a[mid] | comparison | action |
|---|---|---|---|---|---|
| 1 | (0, 5) | 2 | 11 | 12 > 11 | search right |
| 2 | (3, 5) | 4 | 17 | 12 < 17 | search left |
| 3 | (3, 3) | 3 | 12 | 12 = 12 | found at position 3 |
Had the last comparison failed, the search would continue in an empty sub-list on the left or right, concluding that the element is absent.
Recursive implementation
A helper function works on the interval [start, end]; the public function sets up the full interval.
# helper recursive function
def bin_search(a, start, end, target):
if start > end:
return -1 # NOT FOUND -> base case 1
mid = (start + end) // 2 # about in the middle
middle = a[mid]
if middle == target:
return mid # FOUND -> base case 2
elif middle < target:
# SEARCH ON THE RIGHT
return bin_search(a, mid + 1, end, target)
else:
# SEARCH ON THE LEFT
return bin_search(a, start, mid - 1, target)
# recursively implements binary search
def binary_search(a, target):
return bin_search(a, 0, len(a) - 1, target)There are two base cases: empty interval (start > end, not found, returns -1) and element found (returns mid). Lecture-note examples: with a = [2, 4, 7, 10, 15, 21, 30], binary_search(a, len(a), 15) gives position 4, and searching 8 gives -1.
Loop-based implementation
The recursive binary search is a tail recursion (the recursive call is the last action), so it is easy to turn into a loop. Performance remains .
# loop-based implementation of binary search
def binary_search(a, target):
start = 0
end = len(a) - 1
while start <= end:
mid = (start + end) // 2
middle = a[mid]
if middle == target:
return mid # FOUND
elif middle < target:
start = mid + 1 # SEARCH ON THE RIGHT
else:
end = mid - 1 # SEARCH ON THE LEFT
return -1 # NOT FOUNDPerformance of binary search
On a list of size the algorithm does one comparison with the central element (one access) and then searches a list of size about . With the time complexity:
Solving the recurrence by successive substitution (base case , which must be stated):
The base case is reached when (assuming is a power of 2), i.e. , so . Substituting: . For general (not a power of 2) the result is , where is the floor functionthe largest integer less than or equal to x. Therefore
This holds in the worst cases (the element is in the last one-element sub-list, or is absent) and can be shown to hold on average too (count the accesses in the cases where the element is at position and divide by ). From a million elements to about twenty comparisons: this is the power of the logarithm.
Grafico interattivo: Linear O(n) versus binary O(log n) search
Changing the base of the logarithm
The base of the logarithm can be omitted in big-O notation: changing base only multiplies by a constant.
For example with . Constant factors are ignored in asymptotic notation, so .
Proof. Let , so that . Then . The middle step uses the power rule .
3. Finding the maximum or the minimum
In an unsorted list there is no general shortcut: the maximum could be anywhere, so all elements must be examined (an element not yet read could be larger than the current candidate).
# finds the maximum element in a list
def find_max(a):
max_val = a[0] # first guess: max is at index 0
for i in range(1, len(a)):
if a[i] > max_val:
max_val = a[i] # new max candidate is found
return max_valThe minimum is identical: only the comparison changes from > to <.
# finds the minimum element in a list
def find_min(a):
min_val = a[0] # first guess: min is at index 0
for i in range(1, len(a)):
if a[i] < min_val:
min_val = a[i] # new min candidate is found
return min_valPerformance. If the list has elements the algorithm performs exactly accesses (indices ; index is not valid), regardless of where the max/min is. Best, average and worst case coincide:
(With a = [1, 2, 3, 4, 5] the lecture notes print maximum 5 and minimum 1.)
4. Cost analysis of the sorting algorithms: the model and the notation
The execution time of an algorithm depends on the number and type of machine instructions the processor executes. To do a theoretical analysis without writing the code and translating it into machine language, the slides make a drastic simplification: count the number of read or write accesses to list elements, neglecting the other instructions.
- if there exist constants and such that for : informally, grows at least as for large .
- if is both and : it grows as for large .
- In practice the course uses only big-O, informally, to say that the growth of equals the growth of for large .
Limits of big-O. Two algorithms can both be even if one is a thousand times faster than the other, so big-O tells whether an algorithm is applicable in principle, but a more detailed analysis is needed in practice. The analysis must also consider the actual size of the problem (an algorithm with a better trend for large might need unacceptable time for small ) and distinguish the average case (average execution time) from the worst case (the most "unfortunate" inputs).
5. Selection sort
Idea. Selection sort progressively builds the sorted part of the list. At each step it searches for the minimum in the still-unsorted part and swaps it with the first element of that part. Select the minimum, put it in its place, repeat. The left part becomes sorted and is never modified again. (The slides first sort integers, and then extend the idea to objects instead of numbers.)
Worked trace: [11, 9, 17, 5, 12] in ascending order
- Minimum of the whole list:
5at index 3. Its correct place isa[0]. The11stored ina[0]is moved temporarily toa[3](its final place is not known yet): swapa[3]witha[0]giving[5, 9, 17, 11, 12]. - Left side
[5]is sorted. In the rest the minimum is9ata[1], already in its place: no swap. Now[5, 9 | 17, 11, 12]. - In
a[2], a[3], a[4]the minimum is11ata[3]: swap witha[2], giving[5, 9, 11, 17, 12]. - Remaining
a[3], a[4]: minimum12ata[4]: swap witha[3], giving[5, 9, 11, 12, 17]. - The unsorted side has a single element, so it is obviously sorted.
Code, decomposed into functions
# helper function: finds the position of the minimum
# element in the list a starting from index start
def find_min_pos(a, start):
pos = start
min_val = a[start]
for i in range(start + 1, len(a)):
temp = a[i] # complex method
if temp < min_val: # to simplify the
pos = i # performance evaluation
min_val = temp # see next slides
return pos
# helper function: swaps elements in the list
def swap(a, i, j):
temp = a[i]
a[i] = a[j]
a[j] = temp# sorts a list by using the selection sort algorithm
def selection_sort(a):
for i in range(len(a) - 1):
min_pos = find_min_pos(a, i)
if min_pos != i:
swap(a, min_pos, i)Code, single Python function
def selection_sort(a):
for i in range(len(a) - 1):
# find the position of the minimum element from i to end
pos = i
min_val = a[i]
for j in range(i + 1, len(a)):
if a[j] < min_val:
pos = j
min_val = a[j]
# swap if needed
if pos != i:
a[i], a[pos] = a[pos], a[i]The outer loop stops at len(a) - 1: when one element is left it is already in place. The lecture-note version compares v[j] < v[min_pos] and swaps through temp; on [11, 9, 17, 5, 12] it prints [5, 9, 11, 12, 17].
Performance of selection sort
Count the read/write accesses on a list of elements (ignoring the possible case where the swap is not necessary):
- read accesses to find the first minimum;
- 4 accesses to swap two elements (both are read and written);
- so accesses for the first step; then the remaining list has elements, costing , and so on down to the step with inclusive.
Group the terms: the numbers and, for the steps, . Adding and subtracting the missing term completes the Gauss sumthe formula for the sum of the first n positive integers:
This is a second-degree polynomial, which justifies the parabolic trend of the times measured experimentally.
Gauss sum formula:
Proof (arithmetic). Write the sum twice, once from down to and once from up to , and add column by column: every column sums to and there are columns. So , giving the formula. (Geometric proof of the slides: two staircases of squares fit together in a rectangle .)
Selection sort always performs the same number of comparisons, whatever the data distribution: even if the list is already sorted, it scans every element of the remaining sub-list to find the minimum. So worst, average and best case coincide. It is correct, simple and uses little additional memory, but it is not efficient on large lists. (Lecture notes, same idea: .)
Why study other algorithms? Selection sort is correct and sorts any list of numbers or strings, but there are sorting algorithms that sort faster with the same list size; comparing different algorithms for the same problem is exactly the purpose of the analysis.
6. MergeSort
MergeSort has much better performance than selection sort. It is based on the divide and conquer technique: divide the list into two (approximately) equal parts, recursively sort the two parts, merge the two sorted parts. Divide, sort, merge.
The idea of merging
If two parts of the list are already sorted, a sorted list is easy to build by repeatedly moving the smallest element of either part to a new list: compare the first remaining elements of the two lists, copy the smaller into the result and advance in the list it came from. This is merging. Trace from the slides, merging [5, 7, 9] and [1, 8]:
| compared (left, right) | smaller moved | result so far |
|---|---|---|
| 5, 1 | 1 | [1] |
| 5, 8 | 5 | [1, 5] |
| 7, 8 | 7 | [1, 5, 7] |
| 9, 8 | 8 | [1, 5, 7, 8] |
| 9, (right finished) | 9 | [1, 5, 7, 8, 9] |
Recursive structure
In the general case the two halves are not sorted, but each can be sorted by repeating the process: divide in two, assume both sorted, merge. This always ends in a situation where the parts are truly sorted: when they contain only one element. The recursive algorithm:
- base case: a list with fewer than two elements (empty or one element) is already sorted;
- otherwise divide the list in two (approximately) equal parts, sort the first part with MergeSort (recursive step), sort the second part with MergeSort (recursive step), merge the two sorted parts with the merge algorithm.
Tree of recursive calls (lecture notes) on [5, 2, 4, 1, 3]: it splits into [5, 2] and [4, 1, 3]; [5, 2] into [5] and [2]; [4, 1, 3] into [4] and [1, 3]; [1, 3] into [1] and [3]. Merging back up gives [2, 5], [1, 3], [1, 3, 4] and finally [1, 2, 3, 4, 5].
Code
# sorts a list using the mergesort algorithm
def merge_sort(a):
# base case
if len(a) < 2:
return
# split the list in two halves
mid = len(a) // 2 # divide roughly in half
left = a[:mid] # left part
right = a[mid:] # right part
# recursive steps - double recursion
merge_sort(left) # sorts the left list
merge_sort(right) # sorts the right list
# merge
merge(a, left, right) # the work is left to merge methoddef merge(a, b, c):
ia, ib, ic = 0, 0, 0
# as long as lists b and c have elements to move
while ib < len(b) and ic < len(c):
if b[ib] < c[ic]:
a[ia] = b[ib]
ia += 1
ib += 1
else:
a[ia] = c[ic]
ia += 1
ic += 1
# here one of the two lists has reached the end
while ib < len(b):
a[ia] = b[ib]
ia += 1
ib += 1
while ic < len(c):
a[ia] = c[ic]
ia += 1
ic += 1merge_sort sorts the list in place (it returns nothing): the two halves are sorted and then merge writes the result back into a. The first while runs as long as both b and c have elements to move; when it ends one of them is exhausted, and one of the last two loops copies the remaining elements of the other. Lecture-note usage: a = [5, 2, 4, 1, 3], merge_sort(a, len(a)) and print(a) gives [1, 2, 3, 4, 5] (that version names the arguments v, v1, v2, with i, i1, i2).
Performance of MergeSort
Experimental measurements show MergeSort is much more efficient than selection sort. Theoretical evaluation, counting accesses to list elements:
- the two slicings
a[:mid]anda[mid:]read and write all elements: accesses; - the two recursive calls cost each;
- merging: accesses to write the elements into the sorted list, plus accesses to read (each written element requires reading two elements, one from each list): .
Adding the contributions gives the recurrence
Solving by substitution (base case ):
The base case is reached for : since and ,
MergeSort pays the cost of merging but always halves the problem. becomes much more advantageous than as grows.
Grafico interattivo: Relative cost: n^2 (selection sort) versus n log n (MergeSort)
7. Recurrences and the Master Theorem
When an algorithm contains recursive calls, its execution time is often described by a recurrence relationan equation that expresses T(n) as a function of the execution time on smaller inputs. A very common form is
where is the number of sub-problems, is the size of each sub-problem and is the cost of the work done outside the recursive calls (e.g. dividing the problem or combining the results). The Master Theorem gives an asymptotic estimate of for recurrences of this type. For the recursive algorithms studied so far:
| algorithm | recurrence | complexity |
|---|---|---|
| binary search | ||
| MergeSort | ||
| naive recursive Fibonacci | exponential |
The method used in the course to estimate the time of a recursive algorithm is successive substitution: replace on the right-hand side with the recurrence itself, spot the pattern after steps and stop at the base case.
8. Insertion sort
Idea (like sorting a hand of cards). The sub-list made of the first cell is sorted, being of unit length. The sorted part is then extended to the right: at each step take the first element of the unsorted part and move it to the left until it is in its correct position, shifting the intermediate (larger) elements to the right.
Worked trace: [9, 8, 5, 7, 6]
| step | element inserted | list after the step (sorted part is the left one) |
|---|---|---|
| start | (9 alone is sorted) |
[9, 8, 5, 7, 6] |
| 1 | 8 | [8, 9, 5, 7, 6] |
| 2 | 5 | [5, 8, 9, 7, 6] |
| 3 | 7 | [5, 7, 8, 9, 6] |
| 4 | 6 | [5, 6, 7, 8, 9] |
Code
# sorts a list using the insertion sort algorithm
def insertion_sort(a):
# the loop starts from index 1 because the first element
# does not require attention
for i in range(1, len(a)): # outer loop
# sorted insertion of current element
cur = a[i] # current element is at index i
j = i - 1
# all elements on the left of the current one
# and greater than it are moved to the right
# going from right to left
while j >= 0 and cur < a[j]: # inner loop
a[j + 1] = a[j]
j -= 1
# the current element is inserted in the right position
a[j + 1] = cur # write position for the current elementcur temporarily holds the new element to insert: it is necessary because, during the shifts to the right, the original cell would be overwritten. The lecture-note version uses temp and j = i with the test j > 0 and temp < v[j - 1] (shifting v[j] = v[j - 1], final v[j] = temp); on [5, 2, 4, 6, 1, 3] it gives [1, 2, 3, 4, 5, 6].
Performance of insertion sort
The outer loop makes iterations. At each iteration the algorithm performs 2 accesses outside the inner loop (1 before and 1 after) and 3 accesses per iteration of the inner loop. How many iterations the inner loop makes depends on how the data is distributed in the list.
- Best case: data already sorted. The inner loop never iterates and costs only 1 access to check the condition. Per outer iteration: 2 + 1 accesses, so
- Worst case: data sorted backwards. Each new element must be inserted at position 0, moving all the elements to its left. At outer iteration there are 2 accesses outside the inner loop and inside: (the slide prints the final polynomial as ; the expression just above it, , expands to the polynomial written here. The class is the same either way.)
- Average case: random data. Each inserted element moves on average past half of the elements to its left:
Grafico interattivo: Insertion sort: best case O(n) versus average/worst case O(n^2)
9. Comparison of the sorting algorithms
| Algorithm | Average case | Worst case | Practical note |
|---|---|---|---|
| Selection sort | simple, few swaps, but slow on large lists | ||
| Insertion sort | excellent on already sorted or nearly sorted data | ||
| MergeSort | efficient and stable in growth, but uses extra memory |
- If the list is almost sorted, use insertion sort. Notable example: a list kept sorted for searching, where a new element is inserted every so often and the list is sorted again.
- There is no algorithm that is always best in every situation: the choice depends on the input size, the initial order, the available memory and the simplicity required.
- Selection sort and insertion sort are useful for understanding basic mechanisms and for small lists. MergeSort shows how well-designed recursion can dramatically improve performance.
A few numbers to understand the trends
Comparing , and (the last column is the ratio ):
| 10 | 100 | 33 | 3 |
| 100 | 10 000 | 664 | 15 |
| 1 000 | 1 000 000 | 9 966 | 100 |
| 10 000 | 100 000 000 | 132 877 | 753 |
| 100 000 | 10 000 000 000 | 1 660 964 | 6 021 |
| 1 000 000 | 1 000 000 000 000 | 19 931 569 | 50 172 |
| 10 000 000 | 100 000 000 000 000 | 232 534 967 | 430 043 |
Qualitative order of the growth rates compared in the slides (from slowest to fastest): , , , , .
Grafico interattivo: Growth rates: log n, n, n log n, n^2
10. Recursive Fibonacci and exponential growth
Not all recursive algorithms are efficient. The classic recursive Fibonacci is didactically useful because it shows the problem of repeated calls: to compute fibonacci(n) the same values are recalculated many times.
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(10)) # 55The execution time satisfies
and the growth is exponential: the number of calls grows as a constant multiplied by , where
is the golden ratiothe constant phi, also the limit of F(n+1)/F(n) as n grows, where F(n) is the n-th Fibonacci number (curiosity: ).
| value of | estimated number of calls |
|---|---|
| 10 | about |
| 50 | about |
| 100 | about |
| 500 | about |
| 1000 | about |
Efficient alternatives. Compute Fibonacci with an iterative version, or with a recursive version with memoizationsaving the values already computed so that they are not recalculated. The iterative version requires linear time, :
# iteratively computes fibonacci numbers
def fibonacci_iterative(n):
if n == 0:
return 0
previous = 0
current = 1
for i in range(2, n + 1):
new = previous + current
previous = current
current = new
return currentLecture notes: fibonacci_iterative(10) prints 55 and fibonacci_iterative(50) prints 12586269025.
11. Summary of complexities
| Problem / algorithm | Complexity | Key idea |
|---|---|---|
| Linear search | scans all elements, in the worst case | |
| Binary search | halves the interval at each comparison | |
| Finding maximum/minimum | every element could be the deciding candidate | |
| Selection sort | repeatedly searches for the minimum | |
| Insertion sort, best case | already sorted list, no shifting | |
| Insertion sort, average/worst | many shifts in the inner loop | |
| MergeSort | divides in two and merges linearly | |
| Recursive Fibonacci | exponential | recalculates the same values many times |
12. Review questions (from the slides)
- Why is sorting data a frequent problem in information processing?
- How does linear search work? Which occurrence does it find if the value appears several times?
- Why must all elements be examined to find the maximum of an unsorted list? How does the minimum algorithm differ?
- Describe in words the main idea of selection sort. Why is the minimum of the still-unsorted part searched each time? Why is it correct but not necessarily efficient? What is the purpose of comparing different algorithms for the same problem?
- What is the fundamental idea of MergeSort? What does "roughly equal parts" mean? What is the merge phase? Why is a list with fewer than two elements the base case? Why is it recursive?
- What are the three main phases in the performance analysis of MergeSort, and what does represent? Why is MergeSort while selection sort and insertion sort (average/worst) are ?
- Why is the base of the logarithm not specified in big-O notation?
- What is a recurrence equation, and how does the substitution method estimate the execution time of a recursive algorithm?
- Describe in words the main idea of insertion sort. What does
currepresent? Why are some elements shifted to the right? What does the number of inner-loop iterations depend on? What are the worst and best cases, and why is the sorted case ? - What prerequisite must a list satisfy for binary search? Why is it ? What are the two base cases of
bin_search? - Why does recursive Fibonacci have exponential complexity, and how can the computation be made more efficient?
Versione ripasso
Cost model. Count the reads and writes of list elements and ignore other instructions. Big-O ignores constant factors, so it compares growth; check also the average versus worst case and the actual size . The course uses big-O informally.
Searches
- Linear search (any list): scan left to right and return the first index, or
-1. Worst case accesses, average , best case 1. Still on average. - Binary search (sorted list only): compare with
a[(start + end) // 2]; go right if the target is greater, left if smaller, stop if equal.- Two base cases:
start > endreturns-1; element found returnsmid. - , so . Successive substitution: with , giving .
- Trace: 12 in
[5, 9, 11, 12, 17, 21]: mid 11 (go right), mid 17 (go left), mid 12 found at index 3. - Tail recursive, so a loop version exists with the same .
- The log base only multiplies by a constant: .
- Two base cases:
- Max / min (unsorted list): every element must be read, in all cases. The minimum changes only
>into<.
Selection sort
- Find the minimum of the unsorted part and swap it to the front of that part.
- Accesses: for the first step, then , and so on. Gauss sum: .
- Same number of comparisons whatever the data: best, average and worst case coincide.
- Trace
[11, 9, 17, 5, 12]:[5, 9, 17, 11, 12], no swap,[5, 9, 11, 17, 12],[5, 9, 11, 12, 17].
MergeSort
- Divide in two halves, sort each recursively, merge. Base case: fewer than two elements.
merge: compare the first elements of both halves, copy the smaller one, advance; then copy the leftovers.- Trace: merging
[5, 7, 9]and[1, 8]gives[1, 5, 7, 8, 9]. - , so . Sorts in place, but the slices use extra memory.
Insertion sort
- The left part is sorted; insert the next element by shifting larger elements one place right.
curkeeps the element being inserted, because the shifts overwrite its cell. - Trace
[9, 8, 5, 7, 6]ends at[5, 6, 7, 8, 9]. - Best case (sorted): . Worst case (reversed): . Average: .
Recurrences and Fibonacci
- Form , estimated by the Master Theorem. The course uses successive substitution: substitute again, spot the pattern after steps, stop at the base case.
- Naive Fibonacci grows like , with . The iterative version is ; memoization is the other fix.
Comparison and summary
| Algorithm | Average | Worst | Note |
|---|---|---|---|
| Selection sort | simple, few swaps, slow on large lists | ||
| Insertion sort | excellent on sorted or nearly sorted data | ||
| MergeSort | efficient, uses extra memory |
- Linear search ; binary search ; max/min ; selection sort ; insertion sort best , average and worst ; MergeSort ; naive Fibonacci exponential.
Common mistakes: applying binary search to an unsorted list; expecting selection sort to be faster on sorted data (it always does the same work); reading big-O as an exact running time; treating the naive recursive Fibonacci as efficient.