Sunday, 1 December 2013

Sorting algorithms: selection sort, quick sort, merge sort, and efficiency.

A sorting algorithm is an algorithm that places elements in a list in a certain order.

Selection sort is an algorithm which finds the minimum value and swaps it with the value in the first position. It then scans for the next minimum value, and swaps position with the second position, and so on. It does at most n swaps, so is useful to use where swapping is expensive. Selection sort has an average time complexity of O(n2), thus is not very efficient for large lists.


Quicksort algorithm partitions an array by taking an element as a pivot with all elements smaller than the pivot moved before it and all greater elements coming after the pivot. The lesser and greater sublists are then recursively sorted. It has complexity of O(n log n).

Merge sort algorithm works by comparing every two elements and swaps if the first should come after the second. It then merges each of the resulting lists of two into lists of four, then merges those lists of four and so on until the last two lists are merged into the final sorted list. This algorithm has a worst-case running time of  O(n log n), so is efficient on very large lists.