



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




Today
A “naive” sorting algorithm
Q: Is this a “good” sorting algorithm?
Why is this algorithm bad (i.e., inefficient)?
A Python Implementation of Bubblesort
def swap(a_list, i, j): tmp = a_list[i] a_list[i] = a_list[j] a_list[j] = tmp
def bubble_sort(a_list): n = len(a_list) for i in range(1, n): # passes 1 to n - 1 for j in range(n - i): # comparisons of pass if a_list[j] > a_list[j + 1]: swap(a_list, j, j + 1)
Note we can analyze the procedure to determine the cost
i = n(n − 1) 2
n^2 − n 2
(^1) Note that ∑ni=1 i = n(n 2 +1)
An even better (but still not good) sorting algorithm: Selection sort
The basic idea:
A simple example
Initial list: 29 10 14 13 ( n =4)
Pass 1 Pass 2
13 10 14 29
13 10 14 29 13 10 14 29
Pass 3 13 10 14 29 10 13 14 29
A Python Implementation of Selection Sort def selection_sort(a_list): n = len(a_list) for i in range(0, n - 1): index = 0 for j in range(1, n - i): if a_list[j] >= a_list[index]: index = j swap(a_list, index, n - i - 1)