def merge(list1, list2): """ Given two sorted lists, return sorted collection of both >>> merge([1, 1, 3], [1, 1]) """ (i1, i2) = (0, 0) result = [] while len(result) < len(list1) + len(list2): if list1[i1] < list2[i2]: # COULD CRASH result.append(list1[i1]) if i1 < len(list1): i1 += 1 else: result.append(list2[i2]) if i2 < len(list2): i2 += 1 return result def merge2(list1, list2): """ Given two sorted lists, return sorted collection of both >>> merge([1, 1, 3], [1, 1]) """ (i1, i2) = (0, 0) result = [] while i2 < len(list2) and i1 < len(list1): if list1[i1] < list2[i2]: result.append(list1[i1]) i1 += 1 else: result.append(list2[i2]) i2 += 1 # One of the originals isn't empty, so copy the rest over. if i2 >= len(list2): while i1 < len(list1): result.append(list1[i1]) i1 += 1 else: while i2 < len(list2): result.append(list2[i2]) i2 += 1 return result def mergesort(array): """ Return sorted array """ # NOT in place return [] def main(): import random numbers = range(10) random.shuffle(numbers) print "original : " + str(numbers) numbers = mergesort(numbers) print "sorted : " + str(numbers) if __name__ == "__main__": import doctest doctest.testmod() main()