import random # find the index of the minimum in L def my_min_index(L): curr_min_index = 0 for i in range(1,len(L)): if (L[i] < L[curr_min_index]): curr_min_index = i return curr_min_index # swap the contents of L[i] and L[j] def swap(L, i, j): temp = L[i]; L[i] = L[j]; L[j] = temp # sort a list in O(n^2) time def selection_sort(L): n = len(L) for i in range(n): j = i + my_min_index(L[i:]) swap(L, i, j) # take two sorted lists and create a single sorted list def merge(A, B): result = [] i = 0; j = 0 # correctly interleave the input lists by repeatedly identifying # the smaller one and saving it to our result list while ((i < len(A)) and (j < len(B))): if (A[i] <= B[j]): result.append(A[i]) i = i + 1 else: result.append(B[j]) j = j + 1 # adding two lists just concatenates them, even if one is empty result += B[j:] result += A[i:] return result # sort a list in O(n log n) time def merge_sort(L): n = len(L) # base case: if the list has one element, we don't need to do anything if (n <= 1): return L # recursive case: sort two halves, and merge the result else: A = merge_sort(L[:n/2]) #L[0..n/2-1] B = merge_sort(L[n/2:]) #L[n/2..n-1] return merge(A, B) ''' mylist = ['a','b','c','d','e','f'] print mylist # 0..5 print mylist[2:] #2..5 ''' mylist = range(20) random.shuffle(mylist) print mylist # run selection sort # Works "in place", it sorts the input list selection_sort(mylist) print "mylist after selection_sort: ", mylist mylist = range(20) sortedList = merge_sort(mylist) print "sortedList after merge_sort: ", sortedList