In the past week, I have learned two new sorting functions, quick sort and merge sort. The labs also refreshed my knowledge on selection sort, insertion sort, and bubble sort. Different functions have different efficiency and it's always better for the function to have a faster run time. The efficiency of a function can be represented as big-oh, such as O(lg n). In this blog, I'll be writing about selection sort and merge sort.
For selection sort, insertion sort, and bubble sort, they all have a running time of O(n^2). Selection sort compares each item in the list roughly n times to every other item in order to sort the list. The exact running time for selection_sort(n) is (0.5 n^2 + 1.5 n + 1), but we only look at the highest order, which is n^2. The reason for doing this is because as n becomes too large, the highest order of n is what matters mostly. Therefore, selection sort has a running time of O(n^2).
For merge sort, it has a running time of O(n log n). Merge sort splits the list in half repeatedly until there is only one element, then it starts merging it back together from the ground level. The process of breaking a list in half repeatedly requires a running time of log n for n items. However, this is not the only process that merge sort does. The process of merging the items back together also needs to be taken into account. For n items, it also requires a running time of n for this process. Therefore to sum it up, merge sort requires a running time of O(n log n).
By examining different sorting functions and their running time, I have gained a deeper understanding on how different coding approach can result in a faster and more efficient function.
No comments:
Post a Comment