def test_merge_sort(self): self.assertEqual([0], merge_sort([0])) self.assertEqual([-2,-1,0,1,2], merge_sort([-1,-2,2,1,0])) self.assertEqual(["a"], merge_sort(["a"])) self.assertEqual(["a","b","c","d"], merge_sort(["c","d","b","a"])) self.assertEqual([1,2,3,"a","b","c"], merge_sort(["b","c",2,"a",1,3]))
def test_merge_sort(self): arr1 = [1, 5, 8, 4, 2, 9, 6, 0, 3, 7] arr2 = [] arr3 = [2] arr4 = [0, 1, 2, 3, 4, 5] arr5 = random.sample(range(200), 50) self.assertEqual(merge_sort(arr1), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) self.assertEqual(merge_sort(arr2), []) self.assertEqual(merge_sort(arr3), [2]) self.assertEqual(merge_sort(arr4), [0, 1, 2, 3, 4, 5]) self.assertEqual(merge_sort(arr5), sorted(arr5))
def start_algorithm(): global data if not data: return if(alg_menu.get() == 'Quick sort'): quick_sort(data, 0,len(data) - 1,draw_data,speed_scale.get()) elif alg_menu.get() == 'Bubble sort': bubble_sort(data,draw_data,speed_scale.get()) elif alg_menu.get() == 'Merge sort': merge_sort(data, draw_data, speed_scale.get()) elif alg_menu.get() == 'Insertion sort': insertion_sort(data, draw_data, speed_scale.get()) draw_data(data,[['green'] for x in range(len(data))])
def letter_freq(file): ''' prints the frequency table of each letter in a given file, with its frequency descending- sorted using merge_sort :param file: a plain text file(.txt) :return: prints a frequency table :complexity: O(num of letters in a file): most dominant ''' write_letters(file, file) f = open(file, 'r') my_str = f.read() f.close() my_list = [] for i in range(ord('a'), ord('z') + 1): my_list.append([chr(i), 0]) for char in my_str: my_list[ord(char) - 97][1] += 1 my_list = merge_sort(my_list) my_list.reverse() string = '' for i in range(len(my_list)): string += str(my_list[i][0]) + ' ' + str(my_list[i][1]) + ' ' return string
def binary_search(num_list, var): found_bool = False merge_sort(num_list) # This function sorts the list based on the merge_sort algorithm low_index = 0 high_index = len(num_list)-1 while(low_index<=high_index): mid = (low_index + high_index) // 2 if num_list[mid] == var: found_bool = True break elif num_list[mid] > var: # means the 'var' might be in the upper half high_index = mid -1 mid = (low_index + high_index) // 2 elif num_list[mid] < var: # means the 'var' might be in the lower half low_index = mid + 1 mid = (low_index + high_index) // 2 return found_bool
def one_test(n = 1000): # Generate a single test for binary search max_num = 2e3 A = gen_test(n, max_num) merge_sort(A, 0, n-1) a = random.randint(-max_num, max_num) #idx = binary_search_recur(A, a, 0, n-1) idx = binary_search_iter(A, a) #print(a, idx) if not idx and a not in A: #print("Not found and correct") return True elif A[idx] == a: #print("Found!") return True else: #print("Something went wrong!") return False
def sendData(self, server, data): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.connect((server, PORT)) sock.send(json.dumps(data)+'\n') self.sockets.append(sock) except socket.error: # Sort locally self.sortedData.append(merge_sort(data))
def main(): list_1 = random.sample(range(200000000), 100000) t_1 = time.time() bubble_sort(list_1) t_2 = time.time() print("bubble_sort_took", t_2 - t_1) t_1 = time.time() merge_sort(list_1, 0, 3) t_2 = time.time() print("merge_sort_took", t_2 - t_1) t_1 = time.time() merge_sort_without(list_1, 0, 3) t_2 = time.time() print("merge_sort_without_sentinel_took", t_2 - t_1) t_1 = time.time() insertion_sort(list_1) t_2 = time.time() print("insertion_sort", t_2 - t_1)
def start(): print('Sorting...') global data if not data: return # These if else statements call the function of the selected algorithm if algMenu.get() == 'Quick Sort': quick_sort(data, draw_data, speedScale.get()) elif algMenu.get() == 'Bubble Sort': bubble_sort(data, draw_data, speedScale.get()) elif algMenu.get() == 'Insertion Sort': insertion_sort(data, draw_data, speedScale.get()) elif algMenu.get() == 'Selection Sort': selection_sort(data, draw_data, speedScale.get()) elif algMenu.get() == 'Merge Sort': merge_sort(data, 0, len(data) - 1, draw_data, speedScale.get()) elif algMenu.get() == 'Counting Sort': count_sort(data, draw_data, speedScale.get())
def test_merge_sort(make_random_lists): random_list = make_random_lists for a_list in random_list: sorted_list = merge_sort(a_list) for j in range(len(a_list)): if j == 0: continue else: if sorted_list[j] < sorted_list[j-1]: raise ValueError, sorted_list
def test_merge_sort(make_random_lists): random_list = make_random_lists for a_list in random_list: sorted_list = merge_sort(a_list) for j in range(len(a_list)): if j == 0: continue else: if sorted_list[j] < sorted_list[j - 1]: raise ValueError, sorted_list
def min_distance_1d(points): if len(points) < 2: return None points = merge_sort(points) (pre, cur), points = points[:2], points[2:] min_ds = abs(cur - pre) for pt in points: ds = abs(pt - cur) if ds < min_ds: min_ds = ds cur = pt return min_ds
def start(self): """ This function should be called first to """ # Right now this is hardcodes for only # two computers to process the data. # This client and a server. # Split the data into equal parts for # each computer that is sorting. parts = [] firstHalf = self.data[0:len(self.data)/2] lastHalf = self.data[len(self.data)/2:len(self.data)] self.sendData(self.servers[0], firstHalf) self.sortedData.append(merge_sort(lastHalf))
def start(self): """ Start listening. While data is being sent receive it and store in class variable """ self.socket.listen(1) self.conn, addr = self.socket.accept() print "Connection from ", addr rawData = "" while True: raw = self.conn.recv(16777216) if not raw: break rawData += raw if raw.endswith('\n'): self.data = json.loads(rawData) break # We're done. Send the data back and close the connection print "Merge sorting..." sortedData = json.dumps(merge_sort(self.data)) print "Sending sorted data to client..." self.conn.sendall(sortedData) print "Data send...closing"
def initializeFromList(self, scores): """@note Build a rank from scores. @param[in] scores a list @return a list @retval list @raises: ValueError, TypeError @example self.initializeFromList([0.34,.05,.6]) """ try: # Review after AD1 - 2018.09.12 - changelog for this method # add score is None if not (len(scores)) or any(d is None for d in scores) or scores is None: raise TypeError( 'Scores vazio ou contém elemento None ou valores duplicados!' ) if len(scores) != len(set(scores)): raise TypeError( 'Scores vazio ou contém elemento None ou valores duplicados!' ) except TypeError: #raise Exception('Scores vazio ou contém elemento None!') print( 'Scores vazio ou contém elemento None ou valores duplicados!') else: self.ranking = scores self._inversoes = self.setComputa_inversoes ranking = [0] * len(scores) count = 0 ordenada = merge_sort(scores) # n. log n # Faz pesquisa binária em tempo n. log n for x in scores: # loop n #ranking[count] = len(scores) - binarySearch(ordenada, x) # pesquisa log n ranking[count] = (len(scores)) - binarySearch( ordenada, x) # pesquisa feita em log n count += 1 # resultado da busca binaria n . log n self.ranking = ranking return self.ranking
def initializeFromTuple(self, rank): """@note Build a rank from tuple. @param[in] rank a tuple @return a list @retval list @raises: ValueError, TypeError @example self.initializeFromTuple((0.34,.05,.6)) """ try: # Review after AD1 - 2018.09.12 - changelog for this method # add rank is None if not (len(rank)) or any(d is None for d in rank) or rank is None: raise TypeError("Ranking contém None ou valores duplicados") #raise Exception("Ranking contém None ou valores duplicados") if len(rank) != len(set(rank)): raise TypeError("Ranking contém None ou valores duplicados") #raise Exception("Ranking contém None ou valores duplicados") except TypeError: #raise TypeError("Ranking contém None ou valores duplicados") print("Ranking contém None ou valores duplicados") #raise # raise Exception("Ranking contém None ou valores duplicados") #raise else: lista = list(rank) self.ranking = lista self._inversoes = self.setComputa_inversoes ranking = [0] * len(rank) count = 0 ordenada = merge_sort(lista) # n. log n # Faz pesquisa binária em tempo n. log n for x in lista: # loop n ranking[count] = len(rank) - binarySearch( ordenada, x) #+ 1 # pesquisa log n count += 1 # resultado da busca binaria n . log n self.ranking = ranking return self.ranking
def test_reverse_order(): new_arr = merge_sort([8,7,6,5,4,3,2,1]) assert new_arr == [1,2,3,4,5,6,7,8]
def test_negative_sorted(): new_arr = merge_sort([-1,-2,-3,-4,-5,-6,-7,-8]) assert new_arr == [-8,-7,-6,-5,-4,-3,-2,-1]
def test_mixed_sorted(): new_arr = merge_sort([-1,2,-3,-46,65,-6,17,-8]) assert new_arr == [-46,-8,-6,-3,-1,2,17,65]
def test_all_zero_input(self): data = [0]*100 merge_sort(data) for i in range(0, 100): self.assertEqual(data[i], 0)
def test_sorting_letters(self): self.assertEqual(["a"],merge_sort(["a"])) self.assertEqual(['C','E','T','b','c','k'],merge_sort(['T','C','c','k','E','b']))
def test_zero_input(self): data = [] merge_sort(data) self.assertEqual(data, [])
import random import copy from insertion_sort import * from merge_sort import * from quick_sort import * if __name__ == "__main__": arr = [random.randint(0, 100) for i in range(10)] print(arr) print(insertion_sort(copy.deepcopy(arr))) print(arr) print(merge_sort(copy.deepcopy(arr))) print(arr) print(quick_sort(copy.deepcopy(arr), 0, len(arr)-1))
import random from insertion_sort import * from selection_sort import * from merge_sort import * my_randoms = random.sample(range(1, 100000000), 1000) print(my_randoms) print(insertion_sort(my_randoms)) selection_sort(my_randoms) selection_sort_2(my_randoms) print(merge_sort(my_randoms))
def test_double_input(self): data = rand_list(count=2) merge_sort(data) self.assertLessEqual(data[0], data[1])
def test_merge_sort(self): eq_(merge_sort([1, 5, 3, 2, 8, 7, 6, 4]), [1, 2, 3, 4, 5, 6, 7, 8]) eq_(merge_sort([100, 3, 9]), [3, 9, 100]) eq_(merge_sort([]), []) eq_(merge_sort([123]), [123]) eq_(merge_sort([1, 1, 1, 1]), [1, 1, 1, 1])
def test_merge_sort_random(self): unsortedlist = [int(1000*random.random()) for i in range(100)] sortedlist = unsortedlist[:] # [:] creates copy of list sortedlist.sort() self.assertEqual(merge_sort(unsortedlist), sortedlist)
def test_merge_sort(self): # can not use range() for Python 3 compatibility self.assertEqual(merge_sort([2,3,1]), [1,2,3]) self.assertEqual(merge_sort(([3,5,6,7,2,1,0,4,8,9])), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
import time lista = random.sample(range(18, 50), 10) lista2 = lista[:] print("***********") print("Caso de teste idade: ") print(lista) print("***********") antes = time.time() print("Ordenado em decrescente (Quick_Sort):") quicksort(lista) depois = time.time() print("Quick Sort demorou ", depois-antes) print(lista) print("***********") antes1 = time.time() print("Ordenado em decrescente (Merge_Sort):") merge_sort(lista2) depois1 = time.time() print("Marge Sort demorou ",depois1-antes1) print(merge_sort(lista2)) print("***********")
def test_all_same_input(self): single_val = rand_list(count=1)[0] data = [single_val]*100 merge_sort(data) for i in range(0, 100): self.assertEqual(single_val, data[i])
def test_already_sorted(): new_arr = merge_sort([1,2,3,4,5,6,7,8]) assert new_arr == [1,2,3,4,5,6,7,8]
def test_single_input(self): data = rand_list(count=1) data_cp = data[:] merge_sort(data) self.assertEqual(data, data_cp)
from merge_sort import * def search(ar, n): if len(ar) in [0, 1]: if ar == []: print('error') return -1 if ar[0] != n: print('error') return -1 if n == ar[len(ar) // 2]: return len(ar) // 2 if n > ar[len(ar) // 2]: beer = search(ar[len(ar) // 2 + 1:], n) if beer == -1: return -1 return len(ar) // 2 + 1 + beer if n < ar[len(ar) // 2]: return search(ar[:len(ar) // 2], n) while True: raw_a = list(map(int, input().split())) a = merge_sort(raw_a) print(a) n = int(input()) print(search(a, n))
print "-" * 30 print "Selection Sort" print "-" * 30 values1 = values[:] selection_sort(values1) print "-" * 30 print "Insertion Sort" print "-" * 30 values2 = values[:] insertion_sort(values2) print "-" * 30 print "Bubble Sort" print "-" * 30 values3 = values[:] bubble_sort(values3) print "-" * 30 print "Comb Sort" print "-" * 30 values4 = values[:] comb_sort(values4) print "-" * 30 print "Shell Sort" print "-" * 30 values5 = values[:] shell_sort(values5) print "-" * 30 print "Merge Sort" print "-" * 30 values6 = values[:] merge_sort(values6)
print() print('Radix sorted: ') binary_radix_sorted_list = list(original) a = time.time() binary_radix_sorted_list = binary_radix_sort(binary_radix_sorted_list) b = time.time() print(b - a) print_list(binary_radix_sorted_list) test_properties(sorted, binary_radix_sorted_list) print() print("Merge sorted: ") merge_sorted_list = list(original) a = time.time() merge_sorted_list = merge_sort(merge_sorted_list) b = time.time() print(b - a) print_list(merge_sorted_list) test_properties(sorted, merge_sorted_list) print() print("Quick sorted: ") quick_sorted_list = list(original) a = time.time() quick_sort(quick_sorted_list) b = time.time() print(b - a) print_list(quick_sorted_list) test_properties(sorted, quick_sorted_list) print()
def test_sorting_numbers(self): self.assertEqual([4],merge_sort([4])) self.assertEqual([-7,-4,0,2,3,10,15],merge_sort([2,-4,0,10,15,-7,3]))
from datetime import datetime from insertion_sort import * from merge_sort import * from bubble_sort import * N = 4000 values = [int(random() * N * 1000) for y in range(N)] t1 = datetime.now() bubble_sort(values) t2 = datetime.now() print("bubble sort time: ", (t2 - t1).total_seconds() * 1000) values = [int(random() * N * 1000) for y in range(N)] t1 = datetime.now() insertion_sort(values) t2 = datetime.now() print("insert sort time: ", (t2 - t1).total_seconds() * 1000) values = [int(random() * N * 1000) for y in range(N)] t1 = datetime.now() merge_sort(values, 0, len(values) - 1) t2 = datetime.now() print("merge sort time: ", (t2 - t1).total_seconds() * 1000) values_benchmark = [int(random() * N) for y in range(N)] t1 = datetime.now() values_sorted = sorted(values_benchmark) t2 = datetime.now() print("builin sorted time: ", (t2 - t1).total_seconds() * 1000)
def test_array_input(self): data = rand_list() merge_sort(data) for i in range(1, len(data)): self.assertLessEqual(data[i-1], data[i])
def test_sorting_symbols(self): self.assertEqual(["!"],merge_sort(["!"])) self.assertEqual(['*','>','?'],merge_sort(['?','*','>']))
def test_sorting_mix(self): self.assertEqual([-6, 5, ',', '/', '?', 'K', 'c'],merge_sort(['/',',','c',5,-6,'K','?']))
def test_merge_sort_empty_array(self): self.assertEqual(merge_sort([]), [])
from merge_sort import * print('Does merge_sort work?') assert merge_sort([4,8,7,7,4,2,3,1]) == [1,2,3,4,4,7,7,8], 'No, it does not' print('Yes it does')
def test_merge_sort_even_length(self): unsortedlist = [3,5,65,62,2,6,5,7] sortedlist = unsortedlist[:] # [:] creates copy of list sortedlist.sort() self.assertEqual(merge_sort(unsortedlist), sortedlist)
def test_merge_sort_single_element(self): self.assertEqual(merge_sort([1]), [1])
for i in range(min_size, max_size + 1): #regenerate array org_arr = increment_size(i) #print(org_arr) #Insertion sort test_arr = copy_arr() start_time = t.time() insert_sort(test_arr) total_time = t.time() - start_time data["insertion_sort"].append(total_time) #merge sort test_arr = copy_arr() start_time = t.time() merge_sort(test_arr) total_time = t.time() - start_time data["merge_sort"].append(total_time) #bubble sort test_arr = copy_arr() start_time = t.time() bubble_sort(test_arr) total_time = t.time() - start_time data["bubble_sort"].append(total_time) #sorted insert sort test_arr = copy_arr() start_time = t.time() sorted_insert_sort(test_arr) total_time = t.time() - start_time
def test_merge_sort_with_elements(self): self.assertEqual(merge_sort([1, 5, 8, 3, 5, 9]), [1, 3, 5, 5, 8, 9]) self.assertEqual(merge_sort([9, 15, 1, 85, 74, 789, 1111, 3, 365]), [1, 3, 9, 15, 74, 85, 365, 789, 1111])
if method == 'count': range_min = 0 A = [] for i in xrange(0,total_len): A.append(random.randint(range_min, range_max)) if print_list: print 'Original Array' print A t = time.time() print 'Start Sorting!' if method == 'heap': heap_sort(A) elif method == 'count': A = count_sort(A, range_max) elif method == 'quick': QSort(A, 0, total_len-1) elif method == 'merge': merge_sort(A, 0, total_len-1) elif method == 'insert': insert_sort(A, 0, total_len-1) #merge_sortion(A, 0, total_lendd-1) usage = time.time() -t print 'Sorted Array, usage=%f' %(usage) if print_list: print A
if __name__ == '__main__': ## Quicksort print('Quicksort:') array = generateArray(20) print(array) quick_sort(array, 0, len(array) - 1) print(array) ## Mergesort print('Mergesort:') array = generateArray(20) print(array) array = merge_sort(array) print(array) ## Selectionsort print('Selectionsort:') array = generateArray(20) print(array) selection_sort(array) print(array) ## Heapsort print('Selectionsort:') array = generateArray(20) print(array) heap_sort(array) print(array)