def test_merge_sort(): numbers = random_list(max_numbers) sorting.merge_sort(numbers) #numbers.dump("after merge_sort()") assert is_sorted(numbers) print("OK merge_sort()")
def test_merge_sort(): """Test the correctness of the function merge_sort""" assert merge_sort([38, 27, 43, 22, 3, 9, 82, 10]) == [3, 9, 10, 22, 27, 38, 43, 82], 'incorrect' assert merge_sort([1, 6, 4, 3, 7, 34, 9]) == [1, 3, 4, 6, 7, 9, 34], 'incorrect'
def negative_markers3(markers, positive): """ Computes the list of negative markers from the list of markers and the list of positive markers. The two lists are sorted. :param markers: The list of markers :type markers: List of String :param positive: The list of positive markers :type positive: List of String :return: The list of negative markers :rtype: List of String """ global cpt negative = [] positive_sorted = sorting.merge_sort( positive, compare) #sort positive markers's list markers_sorted = sorting.merge_sort(markers, compare) #sort markers's list position = 0 #No reinitialization of the position for marker in markers_sorted: found = False while not found and position < len(positive_sorted) and compare( marker, positive_sorted[position]) > -1: #if m>=p if compare(marker, positive_sorted[position]) == 0: #m=p found = True position += 1 cpt += 1 if not found: negative += [marker] return negative
def negative_markers3(markers,positive,give_cmp = False): ''' Third strategy that computes the list of negative markers :param markers: The list of all the markers :type markers: A experience.markers list :param positive: The list of the positive markers :type positive: A experience.experience list :param give_cmp: if set to true, return the number of comparisons and the negative markers :type give_cmp: bool :return: List of negative markers :rtype: list ''' global OP OP = 0 negative = [] markers = sorting.merge_sort(markers, compare) positive = sorting.merge_sort(positive, compare) i = 0 for marker in positive: while compare(markers[i],marker)!=0: negative.append(markers[i]) i += 1 i += 1 while i != len(markers): negative.append(markers[i]) i += 1 if give_cmp: return OP,negative else: return negative
def negative_markers3(markers, positive): """ positiveS = sorting.merge_sort(positive, compare) markersS = sorting.merge_sort(markers, compare) negative = np.array([]) lm = len(markersS) ind = 0 for i in range(lm): c = recherche_dichotomique(markersS[i], positiveS[ind:]) if not c: negative = np.append(negative, markersS[i]) else: ind += 1 return negative """ global cpt positiveS = sorting.merge_sort(positive, compare) markersS = sorting.merge_sort(markers, compare) negative = np.array([]) ind = 0 for marker in markersS: found = False while not found and ind < len(positiveS): c = marker.cmp(positiveS[ind]) cpt += 1 if c == -1: break elif c == 0: found = True ind += 1 if not found: negative = np.append(negative, marker) return negative
def test_merge_sort(): numbers = random_list(max_numbers) print(f"all:{numbers.count()}") print(numbers.dump()) sorting.merge_sort(numbers) assert is_sorted(numbers) print(numbers.dump())
def test_merge_sort(self): data = [14, 2, 8, 6, 1, 3, 5] sorted = [1, 2, 3, 5, 6, 8, 14] merge_sort(data, 0, len(data)) data = [14, 2, 8, 6, 1, 3, 5] sorted = [2, 8, 14, 6, 1, 3, 5] merge_sort(data, 0, 3) self.assertListEqual(data, sorted)
def test_merge_sort(self): numbers = self.random_list( max_numbers) # a randomly generated list is created sorting.merge_sort( numbers ) # call the merge_ sort function with the newly randomly created list as parameter assert self.is_sorted( numbers) # verify that the merge_sort function worked
def test_static_sorts(self): # Note: None of these methods should affect the original lists! original = self.unordered sorting.selection_sort(self.unordered) self.assertEqual(original, self.unordered) sorting.insertion_sort(self.unordered) self.assertEqual(original, self.unordered) sorting.merge_sort(self.unordered) self.assertEqual(original, self.unordered)
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 test_merge_sort(self): collection = utils.random_list(10000, 1, 1000) result = sorting.merge_sort(collection) is_sorted = sorting.isSorted(result) self.assertEqual(True, is_sorted) collection = utils.reversed_sorted_list(1, 10000) result = sorting.merge_sort(collection) is_sorted = sorting.isSorted(result) self.assertEqual(True, is_sorted) collection = utils.sorted_list(1, 10000) result = sorting.merge_sort(collection) is_sorted = sorting.isSorted(result) self.assertEqual(True, is_sorted)
def find_elements_2_sum(value, array): merge_sort(array, 0, len(array)) print(array) for index, element in enumerate(array[:-1]): #print(index, element) # note the value should have negative if element > value: #print("{} too large, stop the loop".format(element)) break else: matched_index = quick_search(array, index + 1, len(array) - 1, value - element) if matched_index is not None: print("found: [{}]=>{}, [{}]=>{}".format(index, element, matched_index, value-element))
def negative_markers2(markers, positive): """ Computes the list of negative markers from the list of markers and the list of positive markers. positive list will be sorted (just the copy). :param markers: The list of markers :type markers: List of String :param positive: The list of positive markers :type positive: List of String :return: The list of negative markers :rtype: List of String """ global cpt negative = [] positive_sorted = sorting.merge_sort( positive, compare) #sort positive markers's list for marker in markers: found = False position = 0 while not found and position < len(positive_sorted) and compare( marker, positive_sorted[position] ) > -1: #If the marker still not been found and at least one positive #marker remaining isn't strictly greater than the marker if compare(marker, positive_sorted[position]) == 0: found = True else: position += 1 cpt += 1 if not found: negative += [marker] return negative
def negative_markers2(markers,positive): negative = [] # Sorting the positive list # positive = sorting.merge_sort(positive, compare) # Starting the for loop with a value from markers list # # and searching for them in the positive list # for val in markers: begin=0 end=len(positive)-1 position = None while begin <= end and position == None: middle = (begin+end)//2 if compare(val,positive[middle]) == -1: end = middle - 1 elif compare(val,positive[middle]) == 1: begin = middle + 1 else: position = middle if position == None: negative.append(val) return negative
def agnostic_binary_search(arr, target): print(f'looking for {target} inside {arr}') sortedArr = merge_sort(arr) print(f'sorted: {sortedArr}') low = 0 high = len(sortedArr) - 1 mid = (low + high) // 2 if target == sortedArr[mid]: return mid if len(sortedArr) == 1: return -1 elif target < sortedArr[mid]: return agnostic_binary_search(sortedArr[:mid], target) else: nextArr = [] if len(sortedArr) == 2: nextArr = sortedArr[1:] else: nextArr = sortedArr[mid:] right_side = agnostic_binary_search(nextArr, target) if right_side >= 0: print(mid + right_side) return mid + right_side else: return -1
def negative_markers2(markers,positive, give_cmp = False): ''' The second strategy that computes the list of negative markers :param markers: The list of all the markers :type markers: A experience.markers list :param positive: The list of the positive markers :type positive: A experience.experience list :param give_cmp: if set to true, return the number of comparisons and the negative markers :type give_cmp: bool :return: List of negative markers :rtype: list ''' global OP OP = 0 negative = [] positive = sorting.merge_sort(positive, compare) for marker in markers: if dicho_search(marker, positive) == -1: negative.append(marker) if give_cmp: return OP,negative else: return negative
def negative_markers3(markers,positive) : negative=np.array([]) ms=sorting.merge_sort(markers,compare) ps=sorting.merge_sort(positive,compare) i=0 m=0 while i<=len(ps)-1: if compare(ms[m],ps[i])==0: i=i+1 else: negative = np.append(negative,ms[m]) m=m+1 while m<len(ms): negative = np.append(negative,ms[m]) m=m+1 return negative
def sort_select(i, input_list): ''' sorts list using merge sort then returns selected ith smallest element (zero indexed) ''' if not 0 <= i <= len(input_list): raise IndexError('Invalid index argument passed. Needs to be in range (0, length of list)') sorted_input = merge_sort(input_list) return sorted_input[i]
def lhyra_sort(data): features = np.array( [len(data), len(data) * log2(len(data) + 1), len(data)**2]) if len(data) > 0 else [0, 0, 0] choice = np.argmin(coeffs @ features + intercepts) if choice == 0: return merge_sort(data, lhyra_hook, {}) elif choice == 1: return insertion_sort(data, lhyra_hook, {}) else: return quick_sort(data, lhyra_hook, {})
def test_example(self): tmpl = [8, 2, 4, 9, 3, 6] a = tmpl[:] expected = [2, 3, 4, 6, 8, 9] actual = sorting.merge_sort(a) self.assertEqual(expected, actual)
def negative_markers2(markers, positive): negative = np.array([]) positive_sorted = sort.merge_sort(positive, compare) for i in markers: index = binary_search(i, positive_sorted) if index[0] != 0: negative = np.append(negative, i) return negative
def test_reversed_100_example(self): tmpl = list(range(0, 1000)) a = list(reversed(tmpl[:])) expected = tmpl[:] actual = sorting.merge_sort(a) self.assertEqual(expected, actual)
def bench(): ex = data.get_data(200) ex2 = [x[:] for x in ex] start = time() sorted_ex = [sorted(x) for x in ex] print("Py time:", time() - start) start = time() lh = lhyra.eval(ex[0], vocal=True) for i in tqdm(range(1, 200)): lh = lhyra.eval(ex[i], vocal=False) print("Lhyra time:", time() - start) start = time() merge_hook = lambda t: merge_sort(t, merge_hook, None) for i in tqdm(range(200)): merge = merge_sort(ex[i], merge_hook, None) print("Merge time:", time() - start) start = time() insert_hook = lambda t: insertion_sort(t, insert_hook, None) for i in tqdm(range(200)): merge = insertion_sort(ex[i], insert_hook, None) print("Insertion time:", time() - start) start = time() quick_hook = lambda t: quick_sort(t, quick_hook, None) for i in tqdm(range(200)): quick = quick_sort(ex[i], quick_hook, None) print("Quick time:", time() - start) start = time() radix_hook = lambda t: radix_sort(t, radix_hook, None) for i in tqdm(range(200)): radix = radix_sort(ex[i], radix_hook, None) print("Radix time:", time() - start) assert (ex == ex2) # Confirming no side effects
def test_merge_sort_random(self): """ Tests merge sort using a list of randomly-ordered numbers. """ numbers = [random.random() for i in range(N_NUMBERS)] # make a copy of the list observed = numbers[:] merge_sort(observed, 0, len(observed) - 1) # make a copy of the list # and sort using built-in function expected = numbers[:] expected.sort() self.assertListEqual(observed, expected)
def negative_markers2(markers, positive): positiveS = sorting.merge_sort(positive, compare) negative = np.array([]) lm = len(markers) for i in range(lm): c = recherche_dichotomique(markers[i], positiveS) if not c: negative = np.append(negative, markers[i]) return negative
def test_merge_sort_sorted(self): """ Tests merge sort using a list of sorted numbers. Ensures that insertion sort maintains the sorted property. """ numbers = [random.random() for i in range(N_NUMBERS)] numbers.sort() # make a copy of the list expected = numbers[:] # make a copy of the list observed = numbers[:] merge_sort(observed, 0, len(observed) - 1) self.assertListEqual(observed, expected)
def negative_markers2(markers,positive): negative = np.array([]) positive_sorted=sorting.merge_sort(positive,compare) for m in range(len(markers)): if not recherche_dichotomique(markers[m],positive_sorted): negative=np.append(negative,markers[m]) return negative
def test_1000_example(self): tmpl = list(range(0, 1000)) a = tmpl[:] random.shuffle(a) expected = tmpl[:] actual = sorting.merge_sort(a) self.assertEqual(expected, actual)
def negative_markers3(markers, positive): negative = np.array([]) markers_sorted = sort.merge_sort(markers, compare) positive_sorted = sort.merge_sort(positive, compare) m_ind = 0 p_ind = 0 while (p_ind < len(positive_sorted)) and (m_ind < len(markers_sorted)): marker = markers_sorted[m_ind] cmp = compare(marker, positive_sorted[p_ind]) if cmp == 0: m_ind += 1 p_ind += 1 elif cmp == -1: negative = np.append(negative, marker) m_ind += 1 else: p_ind += 1 negative = np.append(negative, markers_sorted[m_ind:]) return negative
def negative_markers3(markers, positive): negative = [] m_sort = sorting.merge_sort(markers, compare_cpt) p_sort = sorting.merge_sort(positive, compare_cpt) i = 0 for m in m_sort: find = False while (not find) and i<len(positive): cmp = compare_cpt(m , p_sort[i]) if cmp == 1 : i += 1 elif cmp == 0: find = True else : break if find == False: negative.append(m) return negative
def negative_markers3(markers,positive): negative = [] # Sorting lists markers = sorting.merge_sort(markers, compare) positive = sorting.merge_sort(positive, compare) i,j = 0,0 while i < len(markers) and j < len(positive): if compare(markers[i], positive[j]) == -1: negative.append(markers[i]) i+=1 elif compare(markers[i], positive[j]) == 1: negative.append(markers[i]) j+=1 else: j+=1 i+=1 return negative
def binary_search(numbers, number): sorted_numbers = merge_sort(numbers) half_list = sorted_numbers[:] found = False while not found and half_list: midle_index = (len(half_list)-1)/2 if number == half_list[midle_index]: found = True else: half_list = _get_half_list(half_list, midle_index, number) return found
def binary_search(arr, target, low, high): # Your code here sortedArr = merge_sort(arr) if low > high: return -1 else: mid = (low + high) // 2 if target == sortedArr[mid]: return mid elif target < sortedArr[mid]: return binary_search(sortedArr, target, low, mid - 1) else: return binary_search(sortedArr, target, mid + 1, high)
def test_merge_sort(): l = [ 66, 76, 3, 38, 25, 20, 97, 8, 1, 2, 58, 20, 69, 81, 57, 23, 32, 42, 85, 74, 43, 51, 51, 3, 49, 50, 27, 37, 40, 92 ] expectation = [ 1, 2, 3, 3, 8, 20, 20, 23, 25, 27, 32, 37, 38, 40, 42, 43, 49, 50, 51, 51, 57, 58, 66, 69, 74, 76, 81, 85, 92, 97 ] result = merge_sort(l) assert result == expectation, f"{result}"
def test_performance(): data = sorted(random_list(1000)) for i, v in enumerate(data): index = binary_search_list(data, data[i]) assert index == i data = merge_sort( random_dllist(1000)) # can't get this to work right now... for i in range(data.count()): print(">>>> i=", i) index = binary_search_dllist(data, data.get(i)) print(">>> index=", index, 'data.get(i)=', data.get(i)) assert index == i
def bench(): ex = sorted(random_list()) start = time() py = sorted(ex) print("Py time:", time()-start) start = time() lh = lhyra.eval(ex, vocal=True) print("Lhyra time:", time()-start) start = time() merge_hook = lambda t: merge_sort(t, merge_hook, None) merge_sort(ex, merge_hook, None) print("Merge time:", time()-start) start = time() insert_hook = lambda t: insertion_sort(t, insert_hook, None) insertion_sort(ex, insert_hook, None) print("Insertion time:", time()-start) start = time() quick_hook = lambda t: quick_sort(t, quick_hook, None) quick_sort(ex, quick_hook, None) print("Quick time:", time()-start) start = time() radix_hook = lambda t: radix_sort(t, radix_hook, None) radix_sort(ex, radix_hook, None) print("Radix time:", time()-start)
def generateForSorting(): result = { "input_size": [], "exec_time_insertion": [], "exec_time_merge": [], } dataset = range(10000) for i in range(0, 10000, 10): data = sample(dataset, i) unsorted_copy = data.copy() result["input_size"].append(i) start = time_ns() insertion_sort(data) elapsed = time_ns() - start result["exec_time_insertion"].append(elapsed) start = time_ns() merge_sort(unsorted_copy, 0, len(unsorted_copy)) elapsed_merge = time_ns() - start result["exec_time_merge"].append(elapsed_merge) print(f"{i},{elapsed},{elapsed_merge}") data_frame = pd.DataFrame.from_dict(result) data_frame.to_csv("sorting_data.csv", index=False) plt.figure(1, figsize=(14, 12)) plt.title("Input size vs Exec time") plt.xlabel('Input size') plt.ylabel('Exec time') plt.plot(result["input_size"], result["exec_time_insertion"], c='green', label="Insertion Sort") plt.plot(result["input_size"], result["exec_time_merge"], c='blue', label="Merge Sort") plt.legend() plt.show()
def negative_markers2(markers, positive): positive_l = sorting.merge_sort(positive, compare_cpt) negative = [] for m in markers: a = 0 b = len(positive_l)-1 find = False while (not find) and a <= b: mid = (a+b)//2 comp = compare_cpt(m, positive_l[mid]) if comp == 0: find = True elif comp == -1: b = mid -1 else: a = mid +1 if not find: negative.append(m) return negative
def main(): """ Function that executes program :return: Prints to screen results of algorithms """ # Generate a list xTest = generate_numbers(100000) # Sort it using merge sort and let the user know when the # sorting is finished. xTest = merge_sort(xTest) print "Sorting is finished!" print " " # Execute linear and binary search and print number of comparisons to screen print "Number of comparisons with linear search ... ", lin_search(xTest, 90000) print "Number of comparisons with binary search ... ", bin_search(xTest, 90000, 0) # We now show an example of binary search for perfect power print " " print "The perfect power decomposition of 961 is ", isPerfectPower(961)
def test_merge_sort(self): self.assertEqual([], merge_sort([])) self.assertEqual(bubble_sort([1, 1, 1, 1, 1]), [1, 1, 1, 1, 1]) self.assertEqual(bubble_sort([1, 3, 2, 11, 5]), [1, 2, 3, 5, 11]) self.assertEqual(bubble_sort([5, -1, 0, 2, 3]), [-1, 0, 2, 3, 5]) self.assertEqual(bubble_sort([3]), [3])
def test_merge_sort(): data = populate_random_data() sorting.merge_sort(data) assert sorted(data) == data
def test_merge_sort(self): for arr in random_arrays: self.assertEquals(merge_sort(arr[0]), arr[1])
def test_case_empty(self): unsorted = [] sorted = [] result = sorting.merge_sort(unsorted) self.assertEqual(result, sorted)
def test_case_reverse(self): unsorted = [8, 7, 6, 5, 4, 3, 2, 1] sorted = [1, 2, 3, 4, 5, 6, 7, 8] result = sorting.merge_sort(unsorted) self.assertEqual(result, sorted)
def test_case_same(self): unsorted = [1, 1, 1, 1] sorted = [1, 1, 1, 1] result = sorting.merge_sort(unsorted) self.assertEqual(result, sorted)
def test_case_even(self): unsorted = [1, 3, 5, 7, 2, 4, 6, 8] sorted = [1, 2, 3, 4, 5, 6, 7, 8] result = sorting.merge_sort(unsorted) self.assertEqual(result, sorted)
def test_merge_sort(self): test = sorting.merge_sort(self.unordered) self.assertEqual(test, self.ordered) test = sorting.merge_sort(self.unordered_with_dupes) self.assertEqual(test, self.ordered_with_dupes)
def test_merge_sort(self): for ls in self._ls: assert sorting.merge_sort(list(ls)) == sorted(ls)
def test_sorting_algorithm(self): self.assertEquals(sorting.merge_sort(self.random_list),sorted(self.random_list))
def test_merge_sort(self): sorting.merge_sort(self.list_a) sorting.merge_sort(self.list_b) sorting.merge_sort(self.list_c) sorting.merge_sort(self.list_d) sorting.merge_sort(self.list_one) sorting.merge_sort(self.list_two) self.assertEqual(self.list_a, self.list_sorted) self.assertEqual(self.list_b, self.list_sorted) self.assertEqual(self.list_c, self.list_sorted) self.assertEqual(self.list_d, self.list_sorted) self.assertEqual(self.list_one, [1]) self.assertEqual(self.list_two, [-10, -5])
def test_merge_sort(self): """Tests that test list is correctly sorted.""" self.assertEqual(sorted(self.test_list), merge_sort(self.test_list))
def test_merge_sort(): numbers = random_list(max_numbers) sorting.merge_sort(numbers) assert is_sorted(numbers)