def main(): arr = [9, 2, 6, 4, 3, 5, 1, 4, 6, 3, 7] bubble_sort(arr) for i in range(len(arr)): print("%d" % arr[i])
def benchmark(n=[10, 100, 1000, 10000]): from time import time from bubble_sort import bubble_sort from . import selection_sort ins_times, bub_times, sel_times = [], [], [] for size in n: a = create_array(size, size) t0 = time() bubble_sort(a) t1 = time() bub_times.append(t1 - t0) a = create_array(size, size) t0 = time() selection_sort(a) t1 = time() sel_times.append(t1 - t0) a = create_array(size, size) t0 = time() insertion_sort(a) t1 = time() ins_times.append(t1 - t0) print("\nn\tInsertion\tBubble \tSelection") print(50 * "_") for i, size in enumerate(n): print("%d\t0.5f \t%0.5f \t%0.5f" % (size, ins_times[i], bub_times[i], sel_times[i]))
def testBubble(self): result = copy(self.original) before = time.time() bubble_sort(result) after = time.time() print("Bubble Sort, size: %d time: %f" % (self.list_length, after-before)) self.assertEqual(self.sorted_list, result, "Bubble Sort Failed")
def call_bubble_sort() : global testcase testcase = testset[:] # Make a copy, not a reference, because bubble # sort sorts in place and we want a reproducible # test case bubble_sort.bubble_sort(testcase) # sort in place
def main_test(): testTime = 50000 size = 10 value = 100 succeed = True for i in range(testTime): source = generateRandomArray(size, value) arr1 = copy.copy(source) arr2 = copy.copy(source) bubble_sort(arr1) arr2.sort() if arr1 != arr2: print(source) print(arr1) print(arr2) succeed = False break if succeed: print("success") else: print("fail")
def test_bubble(): sorted_list = [i for i in range(2500)] unsorted = sorted_list.copy() random.shuffle(unsorted) bubble_sort(unsorted) assert_list_equal(sorted_list, unsorted)
def test_bubble_sort(self): arr1 = [1, 5, 8, 4, 2, 9, 6, 0, 3, 7] arr2 = [] arr3 = [0, 1, 2, 3, 4, 5] arr4 = random.sample(range(200), 50) self.assertEqual(bubble_sort(arr1), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) self.assertEqual(bubble_sort(arr2), []) self.assertEqual(bubble_sort(arr3), [0, 1, 2, 3, 4, 5]) self.assertEqual(bubble_sort(arr4), sorted(arr4))
def setUp(self): self.unsorted_seq = ['9', '2', '3', '7', '0', '6', '8', '5', '4'] self.unsorted_seq_alt = self.unsorted_seq[:] print("Input: {0}".format(self.unsorted_seq)) self.sorted_seq = sorted(self.unsorted_seq) self.sorted_seq_alt = sorted(self.unsorted_seq_alt) bst.bubble_sort_alt(self.unsorted_seq_alt) bst.bubble_sort(self.unsorted_seq)
def test_bubble_sort(self): lst1 = [1, 2, 3, 4, 5] lst1 = bubble_sort(lst1) self.assertEqual(lst1, [1, 2, 3, 4, 5]) lst2 = [5, 4, 3, 2, 1] lst2 = bubble_sort(lst2) self.assertEqual(lst2, [1, 2, 3, 4, 5]) lst3 = [2, 4, 3, 4, 5, 5, 1] lst3 = bubble_sort(lst3) self.assertEqual(lst3, [1, 2, 3, 4, 4, 5, 5])
def test_bubble_sort(): for i in range(500): array = [] for j in range(i): array.append(random.randrange(-i, i, 1)) temp = array.copy() temp.sort() bubble_sort(array) assert temp == array
def get_running_time(data_list): tic = time.clock() bubble_sort(data_list) toc = time.clock() bsort_running_time = toc - tic tic = time.clock() quick_sort(data_list) toc = time.clock() qsort_running_time = toc - tic return bsort_running_time, qsort_running_time
def startAlgo(): global data #if not data: # return if algMenu.get() == 'Bubble Sort': bubble_sort(data, drawData, speedScale.get()) drawData(data, ['green' for x in range(len(data))]) elif algMenu.get() == 'Merge Sort': merge_sort(data, drawData, speedScale.get()) drawData(data, ['green' for x in range(len(data))]) elif algMenu.get() == 'Quick Sort': quick_sort(data, 0, len(data) - 1, drawData, speedScale.get()) drawData(data, ['green' for x in range(len(data))])
def test_bubble_sort(): unsorted = [] expected = [] bubble_sort(unsorted) assert expected == unsorted unsorted = [2, 1, 3] expected = [1, 2, 3] bubble_sort(unsorted) assert expected == unsorted
def test_bubble_sort_reversed(): unsorted = [] expected = [] bubble_sort(unsorted, True) assert expected == unsorted unsorted = [2, 1, 3] expected = [3, 2, 1] bubble_sort(unsorted, True) assert expected == unsorted
def StartAlgorithm(): global data if not data: return if algMenu.get() == 'Quick Sort': quick_sort(data, 0, len(data) - 1, drawData, speedScale.get()) drawData(data, ['green' for x in range(len(data))]) elif algMenu.get() == "Bubble Sort": bubble_sort(data, drawData, speedScale.get()) elif algMenu.get() == "Merge Sort": merge_sort(data, drawData, speedScale.get()) elif algMenu.get() == "Insertion Sort": insertion_sort(data, drawData, speedScale.get()) drawData(data, ['green' for x in range(len(data))])
def sort_unique(nums, sort="ascend"): nums_copy = nums.copy() bubble_sort(nums_copy, sort) n = len(nums_copy) j = 1 i = 0 while j < n: if nums_copy[j] != nums_copy[i]: nums_copy[i + 1] = nums_copy[j] i += 1 j += 1 nums_unique_sort = np.zeros((i + 1, ), dtype=int) for j in range(i + 1): nums_unique_sort[j] = nums_copy[j] return nums_unique_sort
def test_sort_random_list(): """Test random list of integers.""" from bubble_sort import bubble_sort x = [randint(0, 9) for p in range(0, 9)] s = bubble_sort(x) x.sort() assert s == x
def time_binary_search(): elapsed = 0 size = 0 size_inc = 10000 print('') while elapsed < 60: size += size_inc ints = [random.randrange(0, size) for x in range(size)] start = time.perf_counter() bubble_sort.bubble_sort(ints) end = time.perf_counter() elapsed = end - start print(size, '\t{0:.5f}'.format(elapsed, 'sec.\n'))
def main(): sample = list(np.random.randint(1000, size=2000)) target = sorted(sample) start = timer() bubble = bubble_sort(sample.copy()) end = timer() assert bubble == target print("bubble sort time (ms) %.4f" % ((end - start) * 1000)) start = timer() selection = selection_sort(sample.copy()) end = timer() assert selection == target print("selection sort time (ms) %.4f" % ((end - start) * 1000)) start = timer() merge = merge_sort(sample.copy()) end = timer() assert merge == target print("merge sort time (ms) %.4f" % ((end - start) * 1000)) start = timer() quick = quick_sort(sample.copy(), 0, len(sample) - 1) end = timer() assert quick == target print("quick sort time (ms) %.4f" % ((end - start) * 1000))
def main(): """Função principal que será rodada quando o script for passado para o interpretador.""" # A função abaixo abre o arquivo texto numeros.txt em modo leitura e lê as linhas dele separando # elas em uma lista de strings. with open('números.txt', 'r', encoding='utf8') as arquivo: linhas_do_arquivo = arquivo.readlines() # Pegue a lista de strings e converta todos os valores dentro dela para inteiros. # TODO COLOQUE SEU CÓDIGO AQUI E APAGUE ESSE COMENTÁRIO DEPOIS. for lis in linhas_do_arquivo: linhas_do_arquivo.append(int(lis)) # O Código abaixo chama cada um dos métodos de ordenação na lista original. # Para garantir que a lista original não muda depois de cada uma das chamadas. # Fazemos cópias dela antes de fazer a chamada. # A função process_time serve para marcar o tempo entre uma e outra chamada das funções e vermos # qual das três é mais rápida. lista_copiada = linhas_do_arquivo.copy() tempo_bubble = time.process_time() lista_ordenada_bubble = bubble_sort(lista_copiada) tempo_bubble = time.process_time() - tempo_bubble lista_copiada = linhas_do_arquivo.copy() tempo_merge = time.process_time() lista_ordenada_merge = merge_sort(lista_copiada) tempo_merge = time.process_time() - tempo_merge lista_copiada = linhas_do_arquivo.copy() tempo_selection = time.process_time() lista_ordenada_selection = selection_sort(lista_copiada) tempo_selection = time.process_time() - tempo_selection print('Tempo de demora do Bubble Sort:', tempo_bubble) print('Tempo de demora do Merge Sort:', tempo_merge) print('Tempo de demora do Selection Sort:', tempo_selection) return lista_ordenada_bubble, lista_ordenada_merge, lista_ordenada_selection
def benchmark(n = [10, 100, 1000, 5000, 10000]): """ Benchmark the 6 sorting algorithms """ times = {'bubble':[], 'selection':[], 'merge':[], 'quicksort3':[], 'insertion_swap':[], 'insertion_ass':[]} for size in n: a = create_array(size = size, max_num = 10*size) t0 = clock() bubble_sort(a) t1 = clock() times['bubble'].append(t1-t0) a = create_array(size = size, max_num = 10*size) t0 = clock() selection_sort(a) t1 = clock() times['selection'].append(t1-t0) a = create_array(size = size, max_num = 10*size) t0 = clock() merge_sort(a) t1 = clock() times['merge'].append(t1-t0) a = create_array(size = size, max_num = 10*size) t0 = clock() insertion_sort_swap(a) t1 = clock() times['insertion_swap'].append(t1-t0) a = create_array(size = size, max_num = 10*size) t0 = clock() insertion_sort_assignment(a) t1 = clock() times['insertion_ass'].append(t1-t0) a = create_array(size = size, max_num = 10*size) t0 = clock() quicksort3(a, 0, size) t1 = clock() times['quicksort3'].append(t1-t0) print(98*'_') print("n\tBubble\t Insertion(s)\t\tInsertion(a)\t Merge\tQuicksort3\tSelection") print(98*'_') for i, size in enumerate(n): print("%d\t%5.4f\t %5.4f\t\t %5.4f\t %5.4f\t %5.4f\t %5.4f"%(size, times['bubble'][i], times['insertion_swap'][i], times['insertion_ass'][i], times['merge'][i], times['quicksort3'][i], times['selection'][i]))
def main(): numeros = [25, 20, 17, 25, 28, 19, 18, 25, 100, -6, 7, 110] aluno1 = ['Maria', 44, 'Feminino'] aluno3 = ['Gui FA', 17, 'Masculino'] aluno2 = ['Rogerio', 34, 'Masculino'] alunos = [aluno1, aluno3, aluno2] print(alunos) #plinio_sort(numeros) #bubble_sort(numeros) #bubble_sort(numeros, reverse=True) #bubble_sort_4_sequences(alunos, 1) #q = lambda x:x[1] #bubble_sort(alunos, reverse=True, key=q) bubble_sort(alunos, reverse=False, key=lambda plinio:plinio[2]) print(alunos)
def test_bubble_sort(self): """ Test that it can sort a list of numbers with the bubble algorithm. """ data = [4, 78, 2, 33, 0, 99, 86, 4, 21, 3] expected = [0, 2, 3, 4, 4, 21, 33, 78, 86, 99] output = bubble_sort(data) self.assertEqual(output, expected)
def main(): print "MAIN:" print "*"*40 print_menu() print "*"*40 input_list = [] try: f = open(sys.argv[1], 'r') n = int(f.readline()) for i in range(n): input_list.append(int(f.readline().strip('\n'))) print "IP", input_list except: print "Error : Opening file" print "Exiting the program" sys.exit() try: option = int(raw_input("Select an option : ")) except ValueError: print "Error in selecting the option" if int(option) in [ i+1 for i in range(len(SORTING_LIST)) ]: print "OPTION", option print "SYS", sys.argv if option == 1: print "Bubble Sort" print bubble_sort(input_list) print "DDD", input_list elif option == 4: print "HEAP" print heap_sort(input_list) print input_list from heap_class import MyHeap h = MyHeap() for i in input_list: h.push(i) print h.max_element() h.push(34) h.push(134) h.push(2) print h.max_element() h.extract_max_element() print h.max_element()
def test_sort_lots(): input = [] for x in range(1000): input.append(random.randint(1, 1000)) actual = bubble_sort(input) expected = input expected.sort() assert actual == expected
def start_algorithm(): """Start Sorting algorithm.""" global DATA if not DATA: return chosen_speed = speed_scale.get() if algorithm_menu.get() == 'Bubble Sort': bubble_sort(data=DATA, draw_data=draw_data, time_tick=chosen_speed) elif algorithm_menu.get() == 'Merge Sort': merge_sort(data=DATA, draw_data=draw_data, time_tick=chosen_speed) elif algorithm_menu.get() == 'Quick Sort': quick_sort(DATA, 0, len(DATA)-1, draw_data=draw_data, time_tick=chosen_speed) # Always color the array elements in green after done sorting. draw_data(DATA, ['green' for x in range(len(DATA))])
def start_algo(): global data if not data: return if algmenu.get() == 'Bubble Sort': bubble_sort(data, drawdata, speed_scale.get()) elif algmenu.get() == 'Quick Sort': quick_sort(data, 0, len(data) - 1, drawdata, speed_scale.get()) elif algmenu.get() == 'Insertion Sort': insert_sort(data, drawdata, speed_scale.get()) elif algmenu.get() == 'Selection Sort': selection_sort(data, drawdata, speed_scale.get()) elif algmenu.get() == 'Merge Sort': merge_sort(data, drawdata, speed_scale.get()) for i in range(len(data)): drawdata(data, [ 'salmon' if x == i else 'deep sky blue' for x in range(len(data)) ]) drawdata(data, ['spring green' for x in range(len(data))])
def test_bubblesort(): list1 = [0, 3, 4, 5, 1, 9] list2 = [] list3 = [1] list4 = [0, 1, 2, 3, 4] list5 = [-2, 1, 1, 3, 1] lists = [list1, list2, list3, list4] for listt in lists: sorted_list, sorted_idxs = bubble_sort(np.copy(listt)) assert np.array_equal(np.sort(listt), sorted_list) assert np.array_equal(np.argsort(listt), sorted_idxs)
def main(): '''sort''' if len(sys.argv) < 3: print("bubble_sorter.py n1 n2...") sys.exit(1) nums = [] for item in sys.argv[1:]: nums.append(int(item)) print(nums) nums = bubble_sort.bubble_sort(nums) print(nums)
def find_winner(): array = [] for _ in range(n): array.append(randint(0, n)) temp_list = array.copy() bubble_start_time = time.time() bubble_sort(temp_list, n) bubble_end_time = time.time() bubble_complete_time = bubble_end_time - bubble_start_time temp_list = array.copy() selection_start_time = time.time() selection_sort(temp_list, n) selection_end_time = time.time() selection_complete_time = selection_end_time - selection_start_time temp_list = array.copy() insertion_start_time = time.time() insertion_sort(temp_list, n) insertion_end_time = time.time() insertion_complete_time = insertion_end_time - insertion_start_time temp_list = array.copy() python_sort_start_time = time.time() sorted(temp_list) python_sort_end_time = time.time() python_sort_complete_time = python_sort_end_time - python_sort_start_time print(bubble_complete_time) print(selection_complete_time) print(insertion_complete_time) print(python_sort_complete_time) print('One cycle ended') time_arr = [ bubble_complete_time, selection_complete_time, insertion_complete_time, python_sort_complete_time ] return find_min_index(time_arr)
def test_bubble_sort(self): self.assertEqual(bs.bubble_sort([5, 7, 3]), [3, 5, 7]) self.assertEqual( bs.bubble_sort([16, 235, 1, 25, 90, 1000, 0, 3, 15, 29]), [0, 1, 3, 15, 16, 25, 29, 90, 235, 1000]) self.assertEqual(bs.bubble_sort([0, 1]), [0, 1]) self.assertEqual(bs.bubble_sort([5]), [5]) self.assertEqual(bs.bubble_sort([]), []) self.assertEqual(bs.bubble_sort([0, -1]), [-1, 0])
def verify_min_dist(array_length, array, distances): """Verifies the distance between the closest points. Returns a message if test is successful. Returns False otherwise. The upper diagonal elements of the distance matrix, excluding the diagonal elements, are written to a 1D-array. This array is then sorted and the first element of the sorted array is the minimum distance. """ min_dist, point1, point2 = find_closest_points(array, distances) array_legth_1D, array_distances_1D = matrix_to_1D_array(array_length, distances) array_distances_1D = bubble_sort(array_legth_1D, array_distances_1D) if min_dist == array_distances_1D[0]: print('\nClosest points are',point1, 'and', point2, '.') print('\nDistance between them is', min_dist, 'units.') return "\nDistance between the closest points is verified." else: return False
def test_bubble_sort(): testList = [2, 3, 1] bubble_sort(testList) assert testList == [1, 2, 3] testList = [0, 0, 0, 0] bubble_sort(testList) assert testList == [0, 0, 0, 0] testList = [-9, 2, 5, -1, 11432, 2, 6] bubble_sort(testList) assert testList == [-9, -1, 2, 2, 5, 6, 11432] testList = [21, 1, 26, 45, 29, 28, 2, 9, 16, 49, 39, 27, 43, 34, 46, 40] bubble_sort(testList) assert testList == [ 1, 2, 9, 16, 21, 26, 27, 28, 29, 34, 39, 40, 43, 45, 46, 49 ]
def main(): if len(sys.argv) != 2: print 'usage: ./compare_sort_algos.py --len_of_array' sys.exit(1) len_of_array = sys.argv[1] # This argument has length of the array to be sorted. print len_of_array # Create Random numbers of this length. The random numbers generated are unique. array = random.sample(xrange(10000000), int(len_of_array)) #print array sorted_array = insertion_sort.insertion_sort(array) insertion_time = time.clock() insertion_tot = insertion_time - start_time print ("Insertion Sort %s" % insertion_tot) sorted_array = selection_sort.selection_sort(array) selection_time = time.clock() selection_tot = selection_time - insertion_time print ("Selection Sort %s" % (selection_tot)) sorted_array = bubble_sort.bubble_sort(array) bubble_time = time.clock() bubble_tot = bubble_time - selection_time print ("Bubble Sort %s" % (bubble_tot)) sorted_array_m = merge_sort.merge_sort(array) merge_time = time.clock() merge_tot = merge_time - bubble_time print ("Merge Sort %s" % (merge_tot)) sorted_array_q = quick_sort.quick_sort(array) quick_time = time.clock() quick_tot = quick_time - merge_time print ("Quick Sort %s" % (quick_tot)) sorted_array_h = heap_sort.heap_sort(array) heap_time = time.clock() heap_tot = heap_time - quick_time print ("Heap Sort %s" % (heap_tot)) objects = ('Insertion', 'Selection', 'Bubble', 'Merge','Quick','Heap') y_pos = np.arange(len(objects)) performance = [insertion_tot/merge_tot,selection_tot/merge_tot,bubble_tot/merge_tot,merge_tot/merge_tot,quick_tot/merge_tot,heap_tot/merge_tot] if (sorted_array_m == sorted_array_q): print "Merge and Quick sorts are giving the same sorted array results" plt.bar(y_pos, performance, align='center', alpha=0.5) plt.xticks(y_pos, objects) plt.ylabel('Time taken w.r.t merge sort') plt.title('Sorting Techniques') plt.show()
def test_bubble_sort(): # get data from file print("test bubble sort.") in_data = [] for line in fileinput.input("../../data/sort1.dat"): in_data.append(int(line)) print("in_data", in_data) target_data = in_data.copy() target_data.sort() print("target_data", target_data) from bubble_sort import bubble_sort out_data = bubble_sort(in_data) print("out_data", out_data) assert (out_data == target_data)
def test_string_array(self): input = ['foo', 'bar', 'baz'] output = ['bar', 'baz', 'foo'] self.assertEqual(bubble_sort.bubble_sort(input), output)
def test_bubble_sort(self): result = bubble_sort(self.arr) self.assertEqual(result, self.answer)
def run_sorting(iarray): return bubble_sort(iarray)
from bubble_sort import bubble_sort arr = [3, 1, 5, 4, 20, 7, 6, 10, 9] print arr bubble_sort(arr) print arr
def test_sorted(self): input = [1,2,3,4,5,6] output = [1,2,3,4,5,6] self.assertEqual(bubble_sort.bubble_sort(input), output)
def test_bubble_sort(input_array): return bubble_sort(input_array)
def test_bubble_sort_sorted(self): self.assertTrue(is_sorted(bubble_sort(self.sorted)))
def findC(datafiles, testspecies, bestC): # Interpolate each datafile, generate a matrix from interpolated data nofiles = len(datafiles) nocols = len(testspecies)+1 locs = np.zeros(nocols-1) interpdata = np.zeros((nofiles,nocols)) filesmatrix = np.zeros((nofiles,2)) for ii in range(nofiles): # interpolate for each file dataobj = iof.ProcFile(datafiles[ii]) if ii == 0: titles = dataobj.gettitles() else: titles1 = dataobj.gettitles() np.testing.assert_array_equal(titles1,titles) # Verify that all data files have the same column headers dataobj.interpolate(testspecies, locs, interpdata[ii,:]) filesmatrix[:,0] = interpdata[:,0] # filesmatrix stores file indices in order and interpolated Temps filesmatrix[:,1] = range(nofiles) filesmatC = matrix.Matrix(nofiles,2) for i in range(nofiles): for j in range(2): filesmatC.SetVal(i,j,filesmatrix[i,j]) # Generate combinations matrix combosmatrix = np.zeros((nocols,cs.totnumcoms(nocols-1)+1)) combosmatrix[0,0] = 1 cs.combination_mat(combosmatrix[1:,1:]) # Calculate progress variables progvars = np.dot(interpdata,combosmatrix) # Generate progress variable matrix progVar = matrix.Matrix(nofiles, cs.totnumcoms(nocols-1)+1) for i in range (nofiles): for j in range(cs.totnumcoms(nocols-1)+1): progVar.SetVal(i,j,progvars[i,j]) # Sort PROGVARS and FILESMATRIX by temperature print "Sorting PROGVARS by temperature" sortmethod = 'bubble' if "".join(sortmethod) == 'bubble': sorter = bubble_sort.bubble_sort(progVar) sorter.SetRefColNum(0) sorter.SetSortEndIndex(nofiles) sorter.SetSortStartIndex(0) sorter.generateIndexArray() sorter.extractRefCol() sorter.sort_data() print "Sorting FILESMATRIX by temperature" sortmethod = 'bubble' if "".join(sortmethod) == 'bubble': sorter = bubble_sort.bubble_sort(filesmatC) sorter.SetRefColNum(0) sorter.SetSortEndIndex(nofiles) sorter.SetSortStartIndex(0) sorter.generateIndexArray() sorter.extractRefCol() sorter.sort_data() # Test monotonicity of PROGVARS print "Testing monotonicity \n" length = progvars.shape[1] monoAryPy = np.zeros(length) monoAry = vector.Vector(length) helper.copy_py_to_vector(monoAryPy, monoAry) checker = monocheck.MonoCheck(progVar) # Create MonoCheck object assert checker.CheckStrictMonoticity(0, monoAry) == 0, "CheckStrictMonoticity ran unsuccessfully.\n" # ^ Check which columns of progVar are strictly increasing or strictly decreasing and store result in monoAry # Test for maximum slope if multiple monotonic progress variables are returned checksum = 0 for i in range(length): checksum += monoAry.GetVal(i) if checksum % 3 != 0: raise RuntimeError("Incorrect values in monoAry vector, check monotonicity function.\n") if checksum > 3: print "Testing max slope:" maxchecker = linregression.LinRegression(progVar) #maxchecker = endpointslope.EndPointSlope(progVar) assert maxchecker.MostMonotonic(0, monoAry) == 0, "MostMonotonic ran unsuccessfully.\n" # ^ Distinguish the best monotonic progress variables elif checksum == 0: # Least non-monotonic tests to be implemented in beta version print "Finding least non-monotonic:" monoAry[0] = 1 # Print results monoAryflag = 0 for i in range(length): if monoAry.GetVal(i) == 3.0: # Print best monotonic progress variable if it exists if monoAryflag != 0: raise RuntimeError("Error in contents of monoAry vector: multiple best selected.\n") monoAryflag = 2 bestC[:] = iof.get_progvar(combosmatrix[1:,i], testspecies, locs, i) print 'The best strictly monotonic progress variable is C = %s' % bestC[1][0], for j in bestC[1][1:]: print "+ %s" % j, print '\nThe column numbers of these species are ', bestC[0],', respectively.\n' elif monoAry.GetVal(i) == 1.0: # Otherwise print least non-monotonic progress variable if monoAryflag != 0: raise RuntimeError("Error in contents of monoAry vector.\n") monoAryflag = 1 bestC[:] = iof.get_progvar(combosmatrix[1:,i], testspecies, locs, i) print 'WARNING: no monotonic progress variables found, but proceeding with best alternative.\n' print 'The least non-monotonic progress variable is C = %s' % bestC[1][0], for j in bestC[1][1:]: print "+ %s" % j, print '\nThe column numbers of these species are', bestC[0],', respectively.\n' for i in range(length): # Print/identify other monotonic progress variables if monoAry.GetVal(i) == 2.0: if monoAryflag < 2: raise RuntimeError("Error in contents of monoAry vector.\n") elif monoAryflag == 2: print "Other candidate monotonic progress variables are:" otherC = iof.get_progvar(combosmatrix[1:,i], testspecies, locs, i) print 'C = %s' % otherC[1][0], for j in otherC[1][1:]: print "+ %s" % j, print "\n", monoAryflag = 3 if monoAryflag < 1: # Give error if no best progress variable is found raise RuntimeError("Error: no best progress variable selected.") # Plot results iof.plotCvT(progvars[:,0],progvars[:,bestC[2]]) # Write results for i in range(nofiles): filesmatC.SetVal(i,0,progvars[i,bestC[2]]) return filesmatC
def test_bubble_sort_should_sort_a_list(self): self.assertEqual([1, 2, 3, 4, 5], bubble_sort([4, 2, 3, 5, 1]))
def test_reverse_order(self): items = [9, 8, 7, 6, 5, 4, 3, 2, 1] sorted_items = [1, 2, 3, 4, 5, 6, 7, 8, 9] self.assertEqual(sorted_items, bubble_sort(items))
s = [getrandbits(64) for i in range(int(argv[1]))] print(s) def check(a, b): if a > b: raise Exception('Not sorted: ' + str(a) + ' should not be greater than ' + str(b)) return b answer = int(argv[2]) if answer == 1: sample = copy(s) print "Bubble sort: " bubble_sort(sample) reduce(check, sample) elif answer == 2: sample = copy(s) print "Quick sort: " comparisons, sample = quick_sort(sample) print (sample) print 'Comparisons: ', comparisons reduce(check, sample) elif answer == 3: sample = copy(s) print "Real quick sort: " comparisons, sample = real_quick_sort(sample, 0, len(sample) - 1) print (sample) print 'Comparisons: ', comparisons reduce(check, sample)
copy2 = copy1[:] X_nb.append(val) time = datetime.now() h2.heap_sort_s() time = datetime.now() - time time_heap_i.append(days_hours_minutes(time)) time = datetime.now() h.heap_sort() time = datetime.now() - time time_heap.append(days_hours_minutes(time)) time = datetime.now() bubble_sort(copy1) time = datetime.now() - time time_bubble.append(days_hours_minutes(time)) time = datetime.now() fusion_sort(copy2) time = datetime.now() - time time_fusion.append(days_hours_minutes(time)) val = val * inc; print(X_nb) print(time_heap) print(time_heap_i) print(time_fusion) print(time_bubble)
# read input file print " " fin1 = open('chemtable_inputs') inputs = [line.strip().split('\t') for line in fin1] datafiles = iof.read_input("data files:", inputs) testspecies = iof.read_input("test species:", inputs, 0, ["Y-CO2","Y-CO","Y-H2O"]) # find best progress variable bestC = [] nofiles = len(datafiles) filesmatC = fpv.findC(datafiles, testspecies, bestC) # change so don't have to pre-initialize here # sort FILESMATRIX by progress variable sortmethod = iof.read_input("sort method:", inputs, default = 'bubble') if "".join(sortmethod) == 'bubble': #only bubble sort supported for this version sorter = bubble_sort.bubble_sort(filesmatC) sorter.SetRefColNum(0) sorter.SetSortEndIndex(nofiles) sorter.SetSortStartIndex(0) sorter.generateIndexArray() sorter.extractRefCol() sorter.sort_data() print "\nSorting filesmatrix by C" # Calculate PDF matrix # Get user inputs ZPy = np.genfromtxt(datafiles[0], unpack=False, skip_header=2, delimiter = "\t", usecols = 0) Zmean_grid = iof.read_input("Zmean_grid:", inputs, minargs = 0, default = 'Z') # if no Z_grid is specified, Z and Zmean will be equivalent if "".join(Zmean_grid) == 'Z': ZmeanPy = ZPy else:
def test_empty_array(self): input = [] output = [] self.assertEqual(bubble_sort.bubble_sort(input), output)
def test_array_length_one(self): input = [1] output = [1] self.assertEqual(bubble_sort.bubble_sort(input), output)
start_time = time.time() radix_group_numbers(lst) end_time = time.time() print 'radix sort took', end_time - start_time, 'seconds' start_time = time.time() merge_sort(lst) end_time = time.time() print 'merge sort took', end_time - start_time, 'seconds' start_time = time.time() bubble_sort(lst) end_time = time.time() print 'bubble sort took', end_time - start_time, 'seconds' start_time = time.time() selection_sort(lst) end_time = time.time() print 'selection sort took', end_time - start_time, 'seconds'
def test_bubble_sort(self): self.assertTrue(is_sorted(bubble_sort(create_unsorted(10000))))
import time import random from bubble_sort import bubble_sort bubble_sort_times = [] merge_sort_times = [] for i in range(100): test_string = ''.join(['1234567890qwertyuiopasdfghjklzxcvbnm'[random.randint(0,35)] for j in range(200)]) print test_string start_time = time.clock() bubble_sort(test_string) bubble_sort_times.append(time.clock() - start_time) start_time = time.clock() sorted(test_string) merge_sort_times.append(time.clock() - start_time) bubble_average = sum(bubble_sort_times) / len(bubble_sort_times) merge_average = sum(merge_sort_times) / len(merge_sort_times) print "Bubble Average: %f"%bubble_average print "Merge Average: %f" %merge_average print "Merge sort is %f times faster than bubble sort."%(bubble_average/merge_average)
def test_array_length_two(self): input = [2,1] output = [1,2] self.assertEqual(bubble_sort.bubble_sort(input), output)
# Script for testing algorithms import random import bubble_sort as b l = random.sample(range(10000), 10000) print l print print b.bubble_sort(l)
def test_reverse_sorted(self): input = [6,5,4,3,2,1] output = [1,2,3,4,5,6] self.assertEqual(bubble_sort.bubble_sort(input), output)
import timeit import random from bubble_sort import bubble_sort from quick_sort import quick_sort # Testing the code for different List size N = range(0,1000,5) # time to record the complexity for quick sort and bubble sort time_quick = [] time_bubble = [] for n in N: # Creating a random list of n numbers RList = [] for i in range(0, n): RList.append(int(random.random() * n)) # timing it for quick sort and bubble sort and adding it time_quick and time_bubble respectively t = timeit.Timer(lambda: quick_sort(RList)) time_quick.append(t.timeit(number=1)) t = timeit.Timer(lambda: bubble_sort(RList)) time_bubble.append(t.timeit(number=1)) #writing a final file with Columns being Operations, Time-Quicksort, Time-Bubblesort f = open('dataset.txt','w') for i in range(0,len(N)): f.write(str(N[i])+" " + str(time_quick[i]) + " " + str(time_bubble[i]) + " " + "\n") f.close()
def test_bubble_sort(self): self.assertEqual(bubble_sort.bubble_sort(self._arr), self._res)
def test(): aa = [45, 67, 656, 232, 100, 10, 3, 1] bubble_sort(aa)