def quicksort_vs_bubble(): lista = [] for i in range(40000): random_num = random.randint(0, 40000) lista.append(random_num) start = time.time() quick_sort(lista, 0, len(lista) - 1) end = time.time() print("[QUICKSORT] 40000 (40K) integers random numbers \n [TIME] " + str(end - start)) lista = [] for i in range(40000): random_num = random.randint(0, 40000) lista.append(random_num) start = time.time() bubble_sort(lista, len(lista)) end = time.time() print("[BUBBLESORT] 40000 (40K) integers random numbers \n [TIME] " + str(end - start)) print("\n")
def StartAlgorithm(): global data speed = int(speedScale.get()) if speed == 2: speed = 1.5 elif speed == 3: speed = 0.1 elif speed == 4: speed = 0.05 elif speed == 5: speed = 0.01 elif speed == 6: speed = 0.005 elif speed == 7: speed = 0.001 search = int(searchEntry.get()) if selected_algo.get() == "Bubble Sort": bubble_sort(data, drawData, speed) elif selected_algo.get() == "Selection Sort": selection_sort(data, drawData, speed) elif selected_algo.get() == "Insertion Sort": insertion_sort(data, drawData, speed) elif selected_algo.get() == "Merge Sort": merge_sort(data, 0, len(data) - 1, drawData, speed) drawData(data, ['light green' for x in range(len(data))]) time.sleep(speed) elif selected_algo.get() == "Quick Sort": quick_sort(data, drawData, speed) elif algMenu.get() == 'Linear Search': linear_search(data, search, drawData, speedScale.get()) elif algMenu.get() == 'Binary Search': merge_sort(data, 0, len(data) - 1, drawData, speed) drawData(data, ['red' for x in range(len(data))]) binary_search(data, search, drawData, speedScale.get())
def StartAlgorithm(): global data speed = int(speedScale.get()) if speed == 2: speed = 0.5 elif speed == 3: speed = 0.1 elif speed == 4: speed = 0.05 elif speed == 5: speed = 0.01 elif speed == 6: speed = 0.005 elif speed == 7: speed = 0.001 if selected_algo.get() == "Bubble Sort": bubble_sort(data, drawData, speed) elif selected_algo.get() == "Selection Sort": selection_sort(data, drawData, speed) elif selected_algo.get() == "Insertion Sort": insertion_sort(data, drawData, speed) elif selected_algo.get() == "Merge Sort": merge_sort(data, 0, len(data) - 1, drawData, speed) drawData(data, ['light green' for x in range(len(data))]) time.sleep(speed) elif selected_algo.get() == "Quick Sort": quick_sort(data, drawData, speed)
def StartAlgorithm(): global data if not data: return if algMenu.get() == 'Merge Sort': merge_sort(data, drawData, speedScale.get()) elif algMenu.get() == 'Bubble Sort': bubble_sort(data, drawData, speedScale.egt()) elif algMenu.get() == 'Quick Sort': quick_sort(data, 0, len(data) - 1, drawData, speedScale.get()) drawData(data, ['green' for i in range(len(data))])
def start_algo(): print("Starting Algorithm") global data ss = speedEntry.get() ss = float(ss) # ss = 0.1 if algMenu.get() == 'quick sort': quick_sort(data, 0, len(data) - 1, drawData, ss) elif algMenu.get() == 'Bubble sort': bubble_sort(data, drawData, ss) else: merge_sort(data, drawData, ss)
def StartAlgorithm(): global data if not data: return if select_algortiham.get() == 'Selection Sort': selection_sort(data, drawData, speedScale.get()) elif select_algortiham.get() == 'Bubble Sort': bubble_sort(data, drawData, speedScale.get()) elif select_algortiham.get() == 'Merge Sort': merge_sort(data, drawData, speedScale.get())
def startAlgo(): global list_numbers global selected_algo global speedscale global colorArray if selected_algo.get()==av_list[0]: bubble_sort(list_numbers,draw_in_canvas,float(speedscale.get()),colorArray) elif selected_algo.get()==av_list[1]: merge_sort(list_numbers,0, len(list_numbers)-1,draw_in_canvas,float(speedscale.get())) else: quick_sort(list_numbers,0,len(list_numbers)-1,draw_in_canvas,float(speedscale.get()))
def index(): """Renders HTML file and takes ',' seperated list of numbers as input.""" message = '' if request.method == 'POST': inputs = request.form.get('n').split(",") int_input = list(map(int, inputs)) result = ",".join(list(map(str, bubble_sort(int_input)))) message = result return render_template('index.html', message=message)
def test_bubble_sort(self): self.assertEqual(bubble_sort(test_case_1), test_res_1) self.assertEqual(bubble_sort(test_case_2), test_res_2) self.assertEqual(bubble_sort(test_case_3), test_res_3) self.assertEqual(bubble_sort(test_case_4), test_res_4) self.assertEqual(bubble_sort(test_case_5), test_res_5) self.assertEqual(bubble_sort(test_case_6), test_res_6) self.assertEqual(bubble_sort(test_case_7), test_res_7)
def quicksort_vs_bubble(): lista = [] for i in range(40000): aleatorio = random.randint(0, 40000) lista.append(aleatorio) tempo = time.time() quick_sort(lista, 0, len(lista) - 1) fim = time.time() print("[QUICKSORT] 40000 (40 mil) inteiros Aleatorios\n[TEMPO] "+ str(fim - tempo)) lista = [] for i in range(40000): aleatorio = random.randint(0, 40000) lista.append(aleatorio) tempo = time.time() bubble_sort(lista, len(lista)) fim = time.time() print("[BUBBLESORT] 40000 (40 mil) inteiros Aleatorios\n[TEMPO] "+ str(fim - tempo)) print("\n")
file_nm = "sortedfil.csv" with open(file_nm, "r") as f: file_dat = f.readlines() for sublist in file_dat: for nums in sublist.split(","): inp_arr.append(int(nums)) start_time = time.time() if sel == 1: sorted_array = ss.selection_sort(inp_arr) elif sel == 2: sorted_array = ins.insertion_sort(inp_arr) elif sel == 3: sorted_array = bs.bubble_sort(inp_arr) elif sel == 4: sorted_array, invcount = ms.merge_sort(inp_arr, 0) elif sel == 5: qs.quick_sort(inp_arr, 0, len(inp_arr) - 1) elif sel == 6: is_sort = input("Is the input already sorted(Y/N): ") if not is_sort.upper().strip() == "Y": sorted_arr, x = ms.merge_sort(inp_arr, 0) start_time - time.time() num = int(input("Enter number to search:")) idx, found = bins.binary_search(inp_arr, int(num), 0) if found:
import random from bubblesort import bubble_sort from insertionsort import insertion_sort storage = [random.randint(-30,100) for number in range(10)] print("Before Sort: " , storage) storage_sorted_b = bubble_sort(storage) print("After Sort by Bubble Sort: ", storage_sorted_b ) storage_sorted_i = insertion_sort(storage) print("After Sort by Insertion Sort: ", storage_sorted_i )
""" Driver code to run bubblesort """ from bubblesort import bubble_sort arr = [64, 34, 25, 12, 22, 11, 90] result = bubble_sort(arr) print ("Sorted array is:") for i in result: print ("%d" %i)
sorted(lst) print(time.time() - x) x = time.time() heap_sort(lst) print(time.time() - x) x = time.time() merge_sort_recursion(lst) print(time.time() - x) x = time.time() insertion_sort(lst) print(time.time() - x) x = time.time() selection_sort(lst) print(time.time() - x) x = time.time() bubble_sort(lst) print(time.time() - x) x = time.time()
def startalgorithm(): global data bubble_sort(data, drawData)
def menu(): print(""" Welcome to the Word Jumble Game """) print(" 1 - Play the game") print(" 2 - Browse a word set") print(" 3 - Add a new word set") print(" 4 - Delete a word set") print(" 5 - View high scores") print(" 6 - Exit") choose = int(input("\nChoose an option: ")) if choose == 1: print(""" Unscramble letters to make a word """) #open the file that the sets of words are loaded into and print keys: word_file = shelve.open("allwords.txt") for key in word_file.keys(): print(key) #player inputs name of key to choose the word set they want to play: keyinput = input(""" Choose a set of words: """) #words are the chosen using key from the word file: words = word_file[keyinput] #score initially set to 0: score = 0 #the player gets 10 guesses, since the loop runs 10 times: for i in range(0, 10): #a random word from list is chosen: word = random.choice(words) correct = word jumble = "" #while loop scrambles the word: while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[position + 1:] #print the jumbled word: print(""" The jumble word is: {}""".format(jumble)) guess = input("\nEnter your guess: ") #if player's input is the same as correct answer add 1 to score: if (guess == correct): print("You guessed it. \n") score += 1 #if input is not the same as the correct answer show correct answer: else: print("Incorrect, the word is: {}. \n".format(correct)) print(""" The End """) word_file.close() print("Your score is: {}/10. \n".format(score)) #time format from: http://strftime.org/ currenttime = time.strftime("%H:%M:%S %d/%m/%Y") #open file with scores: score_file = shelve.open("scores.txt") #if list with key 'scores' is not in file, create new list: if "scores" not in score_file: score_file["scores"] = [] #put scores into list s: s = score_file["scores"] #append score and current time to list s: #from https://www.ibisc.univ-evry.fr/~fpommereau/blog/2015-06-01-automating-writeback-to-python-shelve.html s.append((score, currenttime)) #list s is assigned to key: #have to explicitly assign s to key to save scores score_file["scores"] = s #sync to save the shelf and then close it: score_file.sync() score_file.close() press = int(input("\nPress 0 to go back to Main Menu: ")) if press == 0: menu() elif choose == 2: word_file = shelve.open("allwords.txt") print(""" Loaded wordsets: """) #print all available keys on new line: for key in word_file.keys(): print(""" {}""".format(key)) keyinput = input("\nChoose a set of words to browse: ") print(""" {} """.format(keyinput)) #print list of words without commas or brackets: #adapted from: http://stackoverflow.com/questions/13550423/python-printing-without-commas print(" ".join(str(word) for word in word_file[keyinput])) word_file.close() press = int(input("\nPress 0 to go back to Main Menu: ")) if press == 0: menu() elif choose == 3: #user inputs name of file to extract words from: fileinput = input("\nChoose file of words: ") afile = open(fileinput) whole_thing = afile.read() #split string of words by comma: z = whole_thing.split(",") #strip list z of whitespace: s = [x.strip() for x in z] afile.close() keyinput = input("Choose a name for your word set: ") word_file = shelve.open("allwords.txt") #list with chosen keyinput is assigned to list s: word_file[keyinput] = s word_file.sync() word_file.close() print("\nYour word set '{}' has been added".format(keyinput)) press = int(input("\nPress 0 to go back to Main Menu: ")) if press == 0: menu() elif choose == 4: word_file = shelve.open("allwords.txt") print(""" Loaded wordsets: """) #print every key in 'allwords.txt' on new line: for key in word_file.keys(): print(""" {}""".format(key)) keyinput = input("\nChoose a set of words to delete: ") #delete list with the same key as the input: del word_file[keyinput] word_file.sync() word_file.close() print(""" Your word set '{}' has been deleted""".format(keyinput)) press = int(input("\nPress 0 to go back to Main Menu: ")) if press == 0: menu() elif choose == 5: print(""" Highscores """) score_file = shelve.open("scores.txt") #load list of scores into new list for sorting: score_list = score_file["scores"] #sorting function to sort from highest to lowest: #bubble sort code adapted from: http://interactivepython.org/runestone/static/pythonds/SortSearch/TheBubbleSort.html bubblesort.bubble_sort(score_list) #print each tuple on new line: for score in score_list: print(score) score_file.close() press = int(input("\nPress 0 to go back to Main Menu: ")) if press == 0: menu() elif choose == 6: #ends program: #exit function from: https://docs.python.org/2/library/sys.html sys.exit()
# -*- coding: utf-8 -*- """ Created on Mon Nov 23 07:31:49 2020 @author: HASAN NAZIM """ import numpy as np from bubblesort import bubble_sort from mergesort import merge_sort if __name__ == "__main__": A = np.random.randint(-50, 50, 100) #print(A) K1 = bubble_sort(A) print(K1) K2 = np.sort(A) if (np.array_equal(K1, K2)): print("equal-bubblesort") print("======================================") K4 = merge_sort(A) print(K4) K5 = np.sort(A) if (np.array_equal(K4, K5)): print("equal-mergesort")
# print(ls) print("*******************************************") print("QuickSort ") t1 = time.time() qs.quickSort(ls, asc=True) t2 = time.time() print("Cres: ", (t2 - t1)) t1 = time.time() qs.quickSort(ls, asc=False) t2 = time.time() print("Desc: ", (t2 - t1)) print("*******************************************") print("BubbleSort ") t1 = time.time() bs.bubble_sort(ls, asc=True) t2 = time.time() print("Cres: ", (t2 - t1)) t1 = time.time() bs.bubble_sort(ls, asc=False) t2 = time.time() print("Desc: ", (t2 - t1)) print("*******************************************") print("SelectionSort ") t1 = time.time() ss.selectionSort(ls, asc=True) t2 = time.time() print("Cres: ", (t2 - t1)) t1 = time.time() ss.selectionSort(ls, asc=False) t2 = time.time()
def start_algorithim(): global data bubble_sort(data, draw_data, speedScale.get())
def start_bubble(event, canvas, sort, i_count): global arr, count count = 0 i_count["text"] = f"{count}" bubble_sort(arr, draw_data, canvas, sort, count, i_count)
from bubblesort import bubble_sort n = int(input("nhap so phan tu cua mang : ")) if n <= 0: exit() arr = [] for i in range(0, n): x = int(input("nhap gia tri cho phan tu thu %d " % (i))) arr.append(x) print("mang da tao la :") print(arr) print("mang sau khi sap xep la :") print(bubble_sort(arr))
def test_sort(original_array): expected_result = sorted(original_array) for i in range(len(original_array) - 1): assert bubble_sort(original_array) == expected_result
def __get_lowest_and_highest(self, values): sorted_values = bubblesort.bubble_sort(values) lowest_value = sorted_values[0] highest_value = sorted_values[len(values) - 1] return lowest_value, highest_value
def test_already_sorted_list(self): lst = [1, 2, 3] iterations = bubble_sort(lst) self.assertEqual(lst, [1, 2, 3]) self.assertEqual(iterations, 1)
def startAlgorithm(): global data bubble_sort(data, drawData, speedScale.get())
def test_bubble_sort(): """ bubble_sort pytest """ assert bubble_sort([1, 1, 2, 3]) == [1, 1, 2, 3], "Test Failed" #Test 1 assert bubble_sort([1, 2, 1, 3]) == [1, 1, 2, 3], "Test Failed" #Test 2 assert bubble_sort([3, 2, 1, 1]) == [1, 1, 2, 3], "Test Failed" #Test 3 assert bubble_sort([1, 3, 2, 1]) == [1, 1, 2, 3], "Test Failed" #Test 4
import random from bubblesort import bubble_sort from SelectionSort import selection_sort from InsertionSort import insertion_sort elements = random.sample(range(10000),6000) elements_1 = elements[:] elements_2 = elements[:] bubble_sort(elements) #Random Elements List selection_sort(elements_1) insertion_sort(elements_2)
from bubblesort import bubble_sort array = [21, 50, 12, 31, 61, 40, 30] if __name__ == "__main__": print(array) bubble_sort(array) print(array)
import time import random from bubblesort import bubble_sort from insertsort import insert_sort from mergesort import merge_sort from quicksort import quick_sort from heapsort import heap_sort items = [random.randint(-50, 100) for i in range(10)] time0 = time.time() bubble_sort(items) time1 = time.time() insert_sort(items) time2 = time.time() merge_sort(items) time3 = time.time() quick_sort(items) time4 = time.time() heap_sort(items) time5 = time.time() items.sort() time6 = time.time() print() print(" typ │ time [ms] ") print("─────────────────────┼─────────────────────") print(" Bubble sort │ {:.15f}".format(time1 - time0)) print(" Insertion sort │ {:.15f}".format(time2 - time1)) print(" Merge sort │ {:.15f}".format(time3 - time2)) print(" Quicksort │ {:.15f}".format(time4 - time3))
def test_unsorted_list_with_negative_numbers(self): lst = [1, -2, 6, -4] iterations = bubble_sort(lst) self.assertEqual(lst, [-4, -2, 1, 6]) self.assertEqual(iterations, 4)