Sunday, 30 March 2014

Sorting and Efficiency

    Sorting is an important topic in computer science that deals with sorting elements in an array so that they are in some particular order. For example, we could sort an array containing numbers by their sizes, smallest on the left and largest on the right. In order to achieve this, we need to follow some kind of a plan, an algorithm. Depending on the algorithm, the amount of steps we have to take would differ, especially when the number of elements in an array are really large. 

    In order to compare the steps that an algorithm takes, the big-Oh notation is used, which tells us the upper bound of how the number of steps grows as the number elements, n, are increasing. This is expressed as a mathematical function. Because the notation only concerns with how the steps grows, we do not have to care about the constant of the function.

    There are some important sorting algorithms thought for educational purposes. The bubble sort is O(n^2) because in the worst case, for each pass, we need to compare the n - k times, for some integer k greater than 0, which are done n - 1 times. The selection sort, which is a bit different from the Bubble Sort in terms of how the comparison done, the way we iterate through the array is similar. So, the amount of comparison is also similar and it is O(n^2). The same goes for the insertion sort. The merge sort, however, is different and is O(n lg n). This algorithm uses recursion and like the binary search, it divides the an array into halves and then the comparison is done. The comparison takes n times and the division takes lg n times. 

No comments:

Post a Comment