Wednesday, January 28, 2009

Selection Sort in Python

Selection sort is a very simple sorting mechanism. It looks through the remaining items in the input to find the least one and moves it to its final position. It is an in-place sort and has a complexity of O(n²) . Here is an implementation of it in Python.

import types

def doSelectionSort(input):
"Check for a few simple error conditions"
if input == None:
raise Exception("Input cannot be null")
if not type(input) is types.ListType:
raise Exception("Input can only be a List")

"Do the sort"
length = len(input)
if length <= 1: "Input is already sorted" return i = 0 while i < smallest =" i" j =" i" smallest =" j" temp =" input[i]" a =" [3,6,8,2,0,9,5,89,9]" b =" []" c =" (3,4)">

Here is the ouput:
[0, 2, 3, 5, 6, 8, 9, 9, 89]
Input can only be a List

No comments:

Post a Comment