Over the past few week we have been exploring sorting lists efficiency of functions!
A sorting algorithm is an algorithm that rearranges items in a list into ascending order (i.e. smallest items leftmost and largest items rightmost). In class we looked at many different types of sorting algorithms and the drawback of choosing one verses the other. We also learned about how to compare their efficiency.
For example the sorting algorithms we discussed in these past 2 weeks include: Quicksort, Mergesort and Timsort.
#QuickSort def quick(L): if len(L) == 1: pivot = L # there are much better ways of choosing the pivot! smaller_than_pivot = [x for x in L[1:] if x == pivot] larger_than_pivot = [x for x in L[1:] if x == pivot] return quick(smaller_than_pivot) + [pivot] + quick(larger_than_pivot) else: return L
Quicksort works by picking a pivot from the list it can be random or the first element of the list and reordering the list so that values less than the pivot come before it and values greater than the pivot come after it. This process is repeated recursively, to sort the sublists, until the list is fully sorted.
The way MergeSort works is by dividing the list into n sublists then sorting the sublists and then recursively merges the two halves until there is one sorted list. Professor Danny said, Merge sort is very predictable since its Average, Best and Worst cast runtime is big O(n * logn)
The last sorting algorithm we looked at this week is Tim sort. Which works by using either merge and insertion sort depending on the situation. This algorithm is very complex and I can’t properly explain what factors are used to decide which sort should be used for a given input. Think of Tim Sort as an Adaptive merge sorting algorithm with crazy good performance.
Furthermore I have noticed that it is very common for computer programs to look very similar, especially the simple ones. This poses an interesting question. When multiple programming implementations solve the same task but look different, how can we tell which program is better or more efficient than the other? It might seem reasonable that the time required to solve the larger case would be greater than for the smaller case. Now you may be thinking why would we want to solve the same problem different ways, that might raise an Exception!
I can’t believe this fantastic course is almost over! I hope you now have an understanding of how computer scientists measure algorithm performance with regards to input size and time.
Until next time, yours truly, – CodeShark