[1, 2, 3, 4, 5] is sorted: True
[1, 4, 5, 7, 2] is sorted: False
Use a double for loop to compare all pairs of elements in L
The issorted_allpairs function has a time complexity of \(O(n^2)\)
The issorted function has a time complexity of \(O(n)\)
Bubble sort algorithm
def bubblesort(L):for _ inrange(len(L)-1):for i inrange(len(L)-1):if L[i]>L[i+1]: L[i], L[i+1] = L[i+1], L[i]data = [30,100000,54,26,93,17,77,31,44,55,20]print("Is the data sorted?", issorted(data))print(data)bubblesort(data)print("Is the data sorted?", issorted(data))print(data)
Is the data sorted? False
[30, 100000, 54, 26, 93, 17, 77, 31, 44, 55, 20]
Is the data sorted? True
[17, 20, 26, 30, 31, 44, 54, 55, 77, 93, 100000]
Use a double for loop to order all of the elements in L
The bubblesort function has a time complexity of \(O(n^2)\)
Use a while loop containing a for loop to order elements in L
Although it may consume less time for some lists, the bubblesort_stopearly function still has a time complexity of \(O(n^2)\)
Implementing selection sort
def selectionsort(L): n =len(L)for i inrange(n-1): max_index=0for index inrange(n - i):if L[index] > L[max_index]: max_index = index L[n-i-1], L[max_index] = L[max_index], L[n-i-1]data = [30,100000,54,26,93,17,77,31,44,55,20]selectionsort(data)print(data)
[17, 20, 26, 30, 31, 44, 54, 55, 77, 93, 100000]
Key invariant: after \(i\) runs the largest \(i\) elements are in final position
Find maximum element and swap it with last unsorted element
Yet, the selectionsort function still has a time complexity of \(O(n^2)\)
Implementing insertion sort
def insertionsort(L): n =len(L)for i inrange(n): j = n - i -1while j < n -1and L[j]>L[j+1]: L[j], L[j+1] = L[j+1], L[j] j+=1data = [30,100000,54,26,93,17,77,31,44,55,20]insertionsort(data)print(data)
[17, 20, 26, 30, 31, 44, 54, 55, 77, 93, 100000]
Key invariant: after \(i\) runs the last \(i\) elements are in sorted order
May be faster if the list is already sorted (or almost already sorted)
Yet, the insertionsort function still has a time complexity of \(O(n^2)\)
Sorting in Python
X = [3,1,5]Y =sorted(X)print("X:", X)print("Y:", Y)X.sort()print("X:", X)print("Y:", Y)