mathjax

Sunday, January 11, 2015

Selection Sort

This is the Selection Sort algorithm. It works best on small lists, $2<=k<=7$. It is in-place and is a comparison sort. It works by splitting the list in two sublists, the left sublist is sorted, and the right sublist is unsorted, and in each step (each index of the original list) select the smallest item from the right sublist, place it at the beginning (left-most position) of the right sublist, and then move the boundary one. The boundary is the initial index of each step; that is, the boundary is 0 in the first step, 1 in the second step, and so on. 
def selection_sort(lst):
 for i in xrange(len(lst)):
  m = i
  for j in xrange(i, len(lst)):
   if lst[j] < lst[m]:
    m = j
  #lst[i], lst[m] = lst[m], lst[i]
  swap(lst, i, m)
The Selection sort implementation above provides best case $\Omega(n^2)$ and worst case $O(n^2)$, giving $\Theta(n^2)$ in time complexity.

No comments:

Post a Comment