Monday, 31 March 2014

Sorting to be efficient

There are many search algorithms we have seen during our years in school.  Maybe some of you know more types of searching.  We can see that

Bubble sort is the worst search algorithm most of us has seen.  As a review, bubble sort is when we compare the first number with the second and switch them if the first is larger than the second.  Then we repeat this for the second and third number and so on until we compare the last two numbers in a list.  Then we repeat this process n times where n is the length of the list.  Each time the process is executed, the highest number is dragged to the top, then the second highest is moved before the highest and so on.  Many can see why this algorithm is terrible.  To those that don't, consider this, the list is most likely sorted halfway through the algorithm, and yet the loop will continue to execute, wasting your precious time when you could be enjoying playing other games while you have bubble sort order your list which contains 100000 numbers.  If we examine the runtime of this algorithm, we find that the time as n increases, grows quadratically.

Merge sort is one of the best search algorithms we seen.  As a review, merge sort is when we break up a list into two about equal length (what about when the length of the list is odd?) list and we recursively do this until we have a list of 1 item.  Then the list are sorted individually and combine with its complementary list.  To form the new list from the two smaller list, compare which is the smallest value from the two list and append it to the new list, compare the second smallest value with the value that was not chosen and append the smallest of that and so on until either list have exhausted all values.  This is very efficient and we find that as n increases, the runtime increases logarithmically.

From these two examples of sorting, we can imply that sorting algorithms have different runtime but may grow similarly with another algorithm.  For instance, selection sort and insertion sort has different runtime but as the list increases, the runtime increases at the same rate.  Runtime is important for analysing sorting but this idea can be expanded.  For instances, programmers use it to analyse the program they make.  It is important for a programmer to know the runtime so that he/she can make it more efficient unless you like to wait for a large amount of time for one process to be finished.

No comments:

Post a Comment