from tool import testtime, randomlist, issorted ''' time complexity: Ω(n); Θ(n^2); O(n^2) space complexity: O(1) insertion sort works very well wtih sorted list, how every, the it takes n^2 time, for unsorted list. ''' @testtime def insertionsort(lst): for i in range(1, len(lst)): tmp = i while tmp > 0 and lst[tmp - 1] > lst[tmp]: lst[tmp - 1], lst[tmp] = lst[tmp], lst[tmp - 1] tmp -= 1 return if __name__ == '__main__': size = 2000 lst = randomlist(size, duplicate=True) insertionsort(lst) print(issorted(lst))
_helper(lst, start, mid) _helper(lst, mid, end) _merge(lst, start, mid, end) def _merge(lst, start, mid, end): left_idx = start right_idx = mid tmp = [] for i in range(end - start): if lst[left_idx] < lst[right_idx]: tmp.append(lst[left_idx]) left_idx += 1 else: tmp.append(lst[right_idx]) right_idx += 1 if left_idx >= mid: tmp += lst[right_idx:end] break elif right_idx >= end: tmp += lst[left_idx:mid] break lst[start:end] = tmp[:] if __name__ == '__main__': size = 10 lst = randomlist(size, duplicate=False) mergesort(lst) print(issorted(lst))
print('--%s--' % (name)) # unsorted list without duplicate values time1 = func(lst1) self.assertTrue(issorted(lst1)) # unsorted list with duplicate values time2 = func(lst2) self.assertTrue(issorted(lst2)) # sorted list without duplicate values time3 = func(lst1) self.assertTrue(issorted(lst1)) # sorted list with duplicate values time4 = func(lst2) self.assertTrue(issorted(lst2)) print('l1: %s ms, l2: %s ms, l1(sorted): %s ms, l2(sorted): %s ms.' % (time1, time2, time3, time4)) if __name__ == '__main__': size = 500 lst1 = randomlist(size, duplicate=True) lst2 = randomlist(size, duplicate=False) lst3 = [i for i in range(size)] test = TestCase() test.testSort(builtinsort, lst1[:], lst2[:], 'built-in sort') test.testSort(mergesort, lst1[:], lst2[:], 'merge sort') test.testSort(quicksort, lst1[:], lst2[:], 'quick sort') test.testSort(insertionsort, lst1[:], lst2[:], 'insertion sort') test.testSort(timsort, lst1[:], lst2[:], 'tim sort') test.testSort(countingsort, lst1[:], lst2[:], 'counting sort')