def testInsertionSort(self): # randomly generate 1000 random numbers in the range -100 to 100 A = [random.randint(-100,100) for c in range(1000)] print("before sort",A) InsertionSort.sort(A) print('After sort',A) for i in range(1, len(A)): if(A[i-1] > A[i]): self.fail('insertion sort method fails')
def sort(self, arr: list) -> list: """ Sorts an array using the bucket sort algorithm Parameters: arr (list): list to be sorted Returns: list: the sorted list """ n = len(arr) buckets = [] for i in range(n): buckets.append([]) for x in arr: index = int(n*x) buckets[index].append(x) ins_sort = InsertionSort() for i in range(n): buckets[i] = ins_sort.sort(buckets[i]) return list(chain.from_iterable(buckets))
for z in range(0, m): # repetition for different orders of array size for i in range(1,n): l = 10**i # order of array size arr = [int(random.random()*100) for j in range(l)] # create an array of random numbers with incremental order alist = [0]*len(arr) # initialize an empty array of same size times[i-1][0] = l # add the order as the first column in the matrix # a loop to go through all the sorting algorithms for g in range(1, 6): start = time.clock() # get a CPU clock tick if g == 1: temp = SelectionSort.sort(dup(alist, arr)) elif g == 2: temp = InsertionSort.sort(dup(alist, arr)) elif g == 3: temp = MergeSort.sort(dup(alist, arr)) elif g == 4: temp = QuickSort.sort(dup(alist, arr)) elif g == 5: temp = CountSort.sort(dup(alist, arr)) end = time.clock() - start # get a CPU clock tick and estimate algorithm r setin(i, end, g) endit = time.clock() - begin # estimate overal calculation time print ('Total time Elapsed:', endit, 'seconds.') # show the benchmark matrix for i in range(0, n-1): print (times[i])
def test_insertion_sort(): sort = InsertionSort() unsorted_numbers = [9,3,5,1,4,5,7] assert_equals(sort.sort(unsorted_numbers), sorted(unsorted_numbers))
def test(self, args): InsertionSort.sort(args) assert InsertionSort.is_sorted(args) InsertionSort.show(args)
# -*- coding: utf-8 -*- import random from timeit import default_timer as timer from insertion_sort import InsertionSort print "-" * 10 + "sorting numbers" + "-" * 10 items = [] for i in range(0, 10): items.append(random.randint(2, 999)) print "original items: %r" % items items = items_worse = range(10 - 1, -1, -1) ssort = InsertionSort(items) # calculate execution time for our selection sort method start = timer() ssort.sort() end = timer() duration1 = end - start # calculate execution time for python built-in sort method start = timer() items.sort() end = timer() duration2 = end - start assert ssort.items == items print "sorted items: %r" % ssort.items print "Duration: our selection sort method - %ds, python builtin sort - %ds" % ( duration1, duration2)
def insertion_sort(array): start = timeit.default_timer() copied_array = copy.copy(array) InsertionSort.sort(array=copied_array) end = timeit.default_timer() return format(end - start, '.5f')