Tuesday, April 1, 2014

Sorting and Efficiency


    The time complexity of a sorting algorithm is correlated to how many steps it has, and how much they are executed based on input. It's possible to find an equation from that information that will give you time depending on input size. If the algorithm is recursive, things get complicated and you have to also consider how many times it will end up calling itself. Once we have this information, it's useful to use things like Big O notation to figure out a limit for how much time the algorithm takes, where, if f(n) is your equation for time taken, f(n) = O(g(n)) if g(n) is some function that, when multiplied by some constant, is always greater than or equal to f(n) as n approaches infinity. For example, if f(n) = 3n^4 + n^2, then f(n) = O(n^4) since, there always exists some constant c where cn^4 >= f(n) for very large n. 

    This can be applied to the sorting algorithms we looked at in class to find out which ones are most efficient, and to figure out ways to improve them. I thought the most interesting contrast was between quick sort and merge sort. At first glance, it seems like they might take a similar amount of time, since they both split the input into two sides. Merge sort works by making a half and half split and then calling a helper function. Meanwhile, quick sort goes through each item individually, placing it behind the original first item if it is less than it, then splits that in half and calls itself recursively on each half. This causes quick sort to run much slower than merge sort since it won't always place items in the correct position before splitting the list in half, so it sometimes does more work than it has to. This is really clear if we look at its worse case scenario, which belongs to O(n^2) while merge sort's is only O(nlogn)