Sorting Algorithms
Sorting In one of the previous posts, we have discussed ' Binary search ' in some detail. One of the requirements to run a Binary Search is that the data in our Array is sorted. In this blog, let's take a look at different ways to sort the lists and find the best way to sort the list. 1. Bubble sort Figure [1] Bubble Sort Here's the code for bubble sorting a simple array: def bubble_sort(array): n = len(array) for i in range(n): already_sorted = True for j in range(n-i-1): if array[j] > array[j+1]: array[j], array[j+1] = array[j+1], array[j] already_sorted = False if already_sorted: break return array print(bubble_sort([2,3,9,8,7,1])) Since the bubble sort algorithm has 2 for loops, it has a time complexity of O(n^2). Figure [2] Time Complexities Graph Based off the graph in Figure 2, we can see that the sorting algorithm has a less desirable time complexity. 2. Insertion sort Fig