Exemplo n.º 1
0
def test_alg(alg, size_array):
    """
    Tests
    """

    t_arrays = []

    # Create the random arrays
    for i in range(N_TESTS_ALG):
        a = [randint(-2**N_BITS, 2**N_BITS) for i in range(size_array)]
        t_arrays.append(a)

    # Insertion Sort
    if alg == INSERTION_SORT:
        print("INSERTION_SORT", end=",")
        print("N=%d" % (size_array))

        # Test N times to get a more precise average time
        for test in range(N_TESTS_ALG):
            A = list.copy(t_arrays[test])
            t1 = time()
            insertion_sort(A)
            t2 = time()
            print("T%d," % test, t2 - t1)

    elif alg == MERGE_SORT:
        print("MERGE_SORT", end=",")
        print("N=%d" % (size_array))

        # Test N times to get a more precise average time
        for test in range(N_TESTS_ALG):
            A = list.copy(t_arrays[test])
            t1 = time()
            merge_sort(A, 0, len(A) - 1)
            t2 = time()
            print("T%d," % test, t2 - t1)

    elif alg == RADIX_SORT:
        print("RADIX_SORT", end=",")
        print("N=%d" % (size_array))

        # Test N times to get a more precise average time
        for test in range(N_TESTS_ALG):
            A = list.copy(t_arrays[test])
            t1 = time()
            radix_sort(A)
            t2 = time()
            print("T%d," % test, t2 - t1)

    elif alg == BUCKET_SORT:
        print("BUCKET_SORT", end=",")
        print("N=%d" % (size_array))

        # Test N times to get a more precise average time
        for test in range(N_TESTS_ALG):
            A = list.copy(t_arrays[test])
            t1 = time()
            bucket_sort(A, len(A))
            t2 = time()
            print("T%d," % test, t2 - t1)
Exemplo n.º 2
0
    def test_merge_sort_error(self):
        # arrange
        arr = 'good morning'

        # action & assert
        with self.assertRaises(TypeError):
            merge_sort(arr)
Exemplo n.º 3
0
def iterations(sort_type, n):  # This function sorts randomly generated numbers of length n that range from -500 to 500
	if sort_type == "selection sort":
		selection_sort.selection_sort([random.randint(-500,500) for number in range(n)])
	elif sort_type == "merge sort":
		merge_sort.merge_sort([random.randint(-500,500) for number in range(n)])
	elif sort_type == "quick sort":
		quick_sort.quick_sort([random.randint(-500,500) for number in range(n)])
Exemplo n.º 4
0
    def test_merge_sort_tests(self):
        '''Test the merge_sort function.'''
        # Test is_sorted
        for i in range(50):
            self.assertTrue(is_sorted(list(range(i))))
        
        # A basic example:
        L = [4,1,0,3,2]
        L = merge_sort(L)
        self.assertTrue(L == list(range(5)))

        # The empty list should be okay
        L = []
        L = merge_sort(L)
        self.assertTrue(L == [])

        # Hopefully it does nothing to already sorted lists:
        L = list('aeiou')
        L = merge_sort(L)
        s = ''.join(L)
        self.assertTrue(s == 'aeiou')

        # Does it shine with multisets?
        L = list('redrum')
        L = merge_sort(L)
        s = ''.join(L)
        self.assertTrue(s == 'demrru')

        # Do a few tests on lists of random integers
        for i in range(3,100):
            L = []
            for j in range(2,i):
                L.append(randint(1,j))
            L = merge_sort(L)
            self.assertTrue(is_sorted(L))
 def test_merge(self):
     unsorted = [5, 4, 3, 2, 1]
     sorted_lst = [1, 2, 3, 4, 5]
     high = len(unsorted) - 1
     low = 0
     merge_sort(unsorted, low, high)
     self.assertEqual(sorted_lst, unsorted)
Exemplo n.º 6
0
 def testMerge(self):
     result = copy(self.original)
     before = time.time()
     merge_sort(result)
     after = time.time()
     print("Merge Sort, size: %d time: %f" % (self.list_length, after-before))
     self.assertEqual(self.sorted_list, result, "Merge Sort Failed")
Exemplo n.º 7
0
def test_merge_sort(seq):
    """Test insertion sort results equal build-in python sort results."""
    from merge_sort import merge_sort
    seq = list(seq)
    sorted_copy = sorted(seq)
    merge_sort(seq)
    assert seq == sorted_copy
def test_big_merge_sort():
    ints = [i for i in range(0, 10000)]
    mixed_ints = [i for i in range(0, 10000)]
    assert ints == mixed_ints
    random.shuffle(mixed_ints)
    assert ints != mixed_ints
    merge_sort(mixed_ints)
    assert ints == mixed_ints
Exemplo n.º 9
0
def sum_search(items, value):
  merge_sort.merge_sort(items, 0, len(items) - 1)
  for i in xrange(0, len(items)):
    last_item = items[-i-1]
    index = binary_search.binary_search(items, value - last_item, 0, len(items) - i - 1)
    if None != index:
      return (items[index], last_item)
  return None
Exemplo n.º 10
0
def has_pair_of_sum_is_v(A, v):
    B = list(A)
    merge_sort(B)
    for i in range(0, len(B) - 1):
        if binary_search(B[i + 1:], v - B[i]) is not None:
            return True
    else:
        return False
Exemplo n.º 11
0
def sum_exist(a,x):
	
	merge_sort(a,0,len(a)-1)
	##print a
	for i in range(len(a)):
		#binary_search(list,begin,end,key)
		if binary_search(a,i,len(a)-1,x-a[i]):
			return True
	return False
def test_merge_sort_edge_case_two():
    arr = ['a', 'c', 'bond', 'b']
    merge_sort(arr)
    assert arr == [
        'a',
        'b',
        'bond',
        'c',
    ]
Exemplo n.º 13
0
def test_stable():
    """Test identical items in list retain stable position on sort."""
    from merge_sort import merge_sort
    check_list = [1, 0, 2, 3, 2]
    two_a = check_list[2]
    two_b = check_list[4]
    merge_sort(check_list)
    assert check_list[2] is two_a
    assert check_list[3] is two_b
Exemplo n.º 14
0
    def test_merge_sort(self):
        # reverse order input
        arr = [5, 4, 3, 2, 1]
        sorted_arr = merge_sort(arr)
        assert sorted_arr == [1, 2, 3, 4, 5]

        # already sorted
        arr = [1, 2, 3, 4, 5]
        sorted_arr = merge_sort(arr)
        assert sorted_arr == [1, 2, 3, 4, 5]
Exemplo n.º 15
0
def test_stable_random(seq):
    """Test stability property on random lists."""
    from merge_sort import merge_sort
    seq = list(seq)
    index_a, index_b = sorted(random.sample(range(len(seq)), 2))
    val_a, val_b = -1, -1
    seq[index_a], seq[index_b] = val_a, val_b
    merge_sort(seq)
    assert seq[0] is val_a
    assert seq[1] is val_b
Exemplo n.º 16
0
def test_stable_random_2(seq):
    """Test that stability fails when sorting to end of list."""
    from merge_sort import merge_sort
    seq = list(seq)
    index_a, index_b = sorted(random.sample(range(len(seq)), 2))
    val_a, val_b = 1000, 1000
    seq[index_a], seq[index_b] = val_a, val_b
    merge_sort(seq)
    assert seq[-1] is val_a
    assert seq[-2] is val_b
Exemplo n.º 17
0
def test(l1, algorithm_no=1):
    start = time.time()

    if algorithm_no == 1:
        ms.merge_sort(l1)
    elif algorithm_no == 2:
        bs.bub_sort(l1)

    end = time.time()
    return (end - start)
def test_merge_sort_edge_case():
    arr = [
        2.5,
        -5,
        0,
        8,
        7,
        9,
    ]
    merge_sort(arr)
    assert arr == [-5, 0, 2.5, 7, 8, 9]
Exemplo n.º 19
0
def test_merge_sort():
    assert (merge_sort([5, 2, 4, 6, 1, 3]) == [1, 2, 3, 4, 5, 6].sort())
    assert (merge_sort([5, 2, 4, 6]) == [2, 4, 5, 6].sort())
    assert (merge_sort([5, 6, 1, 3]) == [1, 3, 5, 6].sort())
    assert (merge_sort([5, 2, 6, 1]) == [1, 2, 5, 6].sort())
    assert (merge_sort([2, 1]) == [1, 2].sort())
    assert (merge_sort([1, 2]) == [1, 2].sort())
    assert (merge_sort([2, 1, 1, 1, 2, 1, 3]) == [1, 1, 1, 1, 2, 2, 3].sort())
    assert (merge_sort([2, 1, 1, 1, 3, 2, 1]) == [1, 1, 1, 1, 2, 2, 3].sort())
    assert (merge_sort([1]) == [1].sort())
    assert (merge_sort([1, 0, -1]) == [1, 0, -1].sort())
Exemplo n.º 20
0
def permute_by_sorting(A):
    B = A.copy()

    n = len(A)
    n3 = n * n * n
    P = [None] * n
    for i in range(n):
        P[i] = (randint(1, n3), i)
    merge_sort(P)
    for i in range(n):
        A[i] = B[P[i][1]]
Exemplo n.º 21
0
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))])
Exemplo n.º 22
0
def measure_runtime(alg, arr):
    if alg == 'merge':
        start_time = time.time()
        merge_sort(arr, 0, len(arr))
        res = time.time() - start_time
    elif alg == 'insert':
        start_time = time.time()
        insertion_sort(arr)
        res = time.time() - start_time

    return res
Exemplo n.º 23
0
def choose_pivot(alist):
    medians = []
    index = 0
    length = len(alist)
    while length > index:
        sorted_group = merge_sort(alist[index:index + 5])
        medians.append(sorted_group[len(sorted_group) / 2])
        index += 5
      
    sorted_medians = merge_sort(medians)
   
    return sorted_medians[len(sorted_medians) / 2]
Exemplo n.º 24
0
    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():
    # even element count
    assert merge_sort([5, 4, 2, 1]) == [1, 2, 4, 5]

    # uneven element count
    assert merge_sort([
        3,
        4,
        5,
        1,
        2,
    ]) == [1, 2, 3, 4, 5]
Exemplo n.º 26
0
 def test_merge_sort(self):
     size = 1000000
     l = list(range(size))
     _l = l[:]
     shuffle(l)
     l2 = l[:]
     t1 = timeit(lambda: merge_sort2(l, 0, len(l) - 1), number=1)
     merge_sort(l, 0, size - 1)
     print("Time to sort with mergesort: " + str(t1))
     #        t2 = timeit(lambda: insertion_sort(l2, 0, len(l2)-1), number=1)
     #        print("Time to sort with insertionsort: " + str(t2))
     self.assertEqual(_l, l)
Exemplo n.º 27
0
def test_merge_sort():
    for i in range(500):
        array = []

        for j in range(i):
            array.append(random.randrange(-i, i, 1))

        temp = array.copy()
        temp.sort()
        merge_sort(array)

        assert temp == array
Exemplo n.º 28
0
def decorated_merge_sort(data, key=None):
    """Sort a sequence using merge-sort, and an optional 'key' to define how sorting should be done."""

    if key is not None:
        for j in range(len(data)):
            data[j] = _Item(k=key(data[j]), v=data[j])

    merge_sort(data)  # Can use any sorting function.

    if key is not None:
        for j in range(len(data)):
            data[j] = data[j]._value
Exemplo n.º 29
0
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))])
Exemplo n.º 30
0
def test_stable_random_3(seq):
    """Test stability property on random lists with random duplicate values."""
    from merge_sort import merge_sort
    if len(seq) < 2:
        return
    seq = list(seq)
    index_a = random.randrange(len(seq) - 1)
    index_b = random.randrange(index_a + 1, len(seq))
    val_a = seq[index_a]
    val_b = int(val_a)
    seq[index_b] = val_b
    merge_sort(seq)
    index_a = seq.index(val_a)
    assert seq[index_a + 1] is val_b
def merge_sort_complexity():
    x, y = [], []

    for i in range(10000, 100000, 10000):
        sample_data = random.sample(range(i), i)

        start_time = time.time()
        merge_sort(sample_data)
        end_time = time.time()

        x.append(i)
        y.append(end_time - start_time)

    plt.plot(x, y)
    plt.show()
Exemplo n.º 32
0
def test_compare():
    """
    Takes 4 different random lists with 10,000 terms in each and runs them
    through each sorting method (insertion, merge, merge_quick, and quick).
    When doing this, the function times how long it takes for each method to
    process each list. The function prints the trials for each list into sectioned
    blocks showing the results for each list for every sorting method.
    :return: None
    """
    print("Time comparison test begins.")
    print("All lists used in this test are of length 10000.")
    print("\n")
    n = 10000
    list_num = 1
    test_lists = [get_list1(n), get_list2(n), get_list3(n), get_list4(n)]
    for i in test_lists:
        if list_num == 1:
            print("Testing with list 1 - random elements")
        elif list_num == 2:
            print("Testing with list 2 - repeated elements")
        elif list_num == 3:
            print(
                "Testing with list 3 - overall increasing elements, not favorable to quick sort"
            )
        elif list_num == 4:
            print("Testing with list 4 - not favorable to quick sort")
        insertion_lst = i[:]
        start = time.time()
        insertion_sort.insertion_sort(insertion_lst)
        end = time.time()
        print("selection_sort Elapsed Time: ", end - start, "seconds")
        merge_lst = i[:]
        start = time.time()
        merge_sort.merge_sort(merge_lst)
        end = time.time()
        print("merge_sort Elapsed Time: ", end - start, "seconds")
        merge_quick_lst = i[:]
        start = time.time()
        merge_quick_sort(merge_quick_lst)
        end = time.time()
        print("merge_quick_sort Elapsed Time: ", end - start, "seconds")
        quick_lst = i[:]
        start = time.time()
        quick_sort.quick_sort(quick_lst)
        end = time.time()
        print("quick_sort Elapsed Time: ", end - start, "seconds")
        print("\n")
        list_num += 1
def test_backward_list():
    """A backward list will return reversed."""
    lst = ['E', 'D', 'C', 'B', 'A']

    expected = ['A', 'B', 'C', 'D', 'E']
    actual = merge_sort(lst)
    assert actual == expected
Exemplo n.º 34
0
def testcase(index, input_array, expected_output):
    print("\n-- testcase {} --".format(index))

    input_array_copy = input_array

    print("input array : {}".format(input_array))
    print("expected output : {}\n".format(expected_output))

    # bst sort
    bst_sort_result = bst_sort(input_array)
    print("bst sort: {}, {}".format(bst_sort_result,
                                    bst_sort_result == expected_output))

    # merge sort
    merge_sort_result = merge_sort(input_array)
    print("merge sort: {}, {}".format(merge_sort_result,
                                      merge_sort_result == expected_output))

    # quick sort
    quick_sort(input_array, 0, len(input_array) - 1)
    print("quick sort: {}, {}".format(input_array,
                                      input_array == expected_output))
    input_array = input_array_copy

    # heap sort
    heap_sort_result = heap_sort(input_array)
    print("heap sort: {}, {}".format(heap_sort_result,
                                     heap_sort_result == expected_output))
def test_empty_list():
    """An empty list will return unchanged."""
    lst = []

    expected = []
    actual = merge_sort(lst)
    assert actual == expected
Exemplo n.º 36
0
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 test_randomly_unsorted_list():
    """An unsorted list returns sorted."""
    lst = ['C', 'B', 'D', 'E', 'A']

    expected = ['A', 'B', 'C', 'D', 'E']
    actual = merge_sort(lst)
    assert actual == expected
Exemplo n.º 38
0
def dselect(array, istat):
    if len(array) <= 5:  # should this be 10?
        sorted_array = merge_sort.merge_sort(array)
        return sorted_array[istat]
    else:
        groups_of_5 = []
        for group_start in range(0, len(array) - 4, 5):
            group = array[group_start:group_start + 5]
            group_median_pos = math.ceil(len(group) / 2) - len(group) % 2
            groups_of_5.append(dselect(group, int(group_median_pos)))
        median_of_medians = dselect(groups_of_5, len(array)//10)
        below = []
        above = []
        pivot = []
        for num in range(len(array)):
            if array[num] == median_of_medians:
                pivot.append(array[num])
            elif array[num] < median_of_medians:
                below.append(array[num])
            else:
                above.append(array[num])
        if istat < len(below):
            return dselect(below, istat)
        elif istat >= len(below) + len (pivot):
            return dselect(above, istat - len(below) - len(pivot))
        else:
            return median_of_medians
Exemplo n.º 39
0
def test_merge():
    sorted_list = [i for i in range(19000)]

    unsorted = sorted_list.copy()
    random.shuffle(unsorted)

    assert_list_equal(sorted_list, merge_sort(unsorted))
Exemplo n.º 40
0
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 test_single_item_list():
    """A one-itemed list will return unchanged."""
    lst = ['A']

    expected = ['A']
    actual = merge_sort(lst)
    assert actual == expected
def test_list_gets_sorted_correctly() -> None:
    to_sort = [random.random() for _ in range(1_000_000)]
    expected = sorted(to_sort)

    actual = merge_sort.merge_sort(to_sort)

    assert actual == expected
Exemplo n.º 43
0
def search(arr, item):
    """Performs binary search on an array
    with the given item and returns True or
    False.
>>> search([5, 4, 1, 6, 2, 3, 9, 7], 2)
    True
>>> search([5, 4, 1, 6, 2, 3, 9, 7], 8)
    False
    """

    arr1 = merge_sort(arr)

    first = 0
    last = len(arr1) - 1
    found = False

    while first <= last and not found:
        midpoint = (first + last) // 2
        if arr1[midpoint] == item:
            found = True
        else:
            if item < arr1[midpoint]:
                last = midpoint - 1
            else:
                first = midpoint + 1

    return found
Exemplo n.º 44
0
def test_sorting():
    import random
    datalist = [random.randint(0, 1e6) for i in xrange(100)]
    datalist = merge_sort(datalist)

    previous = datalist[0]
    for i in datalist[1:]:
        assert previous <= i
        previous = i
Exemplo n.º 45
0
    def sort_merge(self):
        """Sorts the cards in this deck in ascending order

        Uses my my merge_sort"""
        if self.cards:
            self.cards = merge_sort(self.cards)
            return True
        else:
            return False
def run_all(input_directory, output_directory):
    if not os.path.exists(output_directory):
        os.makedirs(output_directory)

    def rel(filename):
        return os.path.join(output_directory, filename)

    # parse_xml(input_directory, rel('articles-raw.csv'), rel('citations-raw.csv'))
    # sanitize(rel('articles-raw.csv'), rel('articles-sanitized.csv'))
    unify_identifiers(rel("articles-sanitized.csv"), rel("articles-id-unified.csv"))
    merge_sort(rel("articles-id-unified.csv"), rel("articles-id-unified-sorted.csv"))
    return
    load_solr(rel("articles-id-unified-sorted.csv"))
    merge_solr(rel("articles-id-unified-sorted.csv"), rel("articles-solr-unified.csv"))
    merge_sort(rel("articles-solr-unified.csv"), rel("articles-solr-unified-sorted.csv"))
    combine_articles(rel("articles-solr-unified-sorted.csv"), rel("articles-tidy.csv"), rel("id-mapping.csv"))
    combine_articles(rel("articles-id-unified-sorted.csv"), rel("articles-tidy.csv"), rel("id-mapping.csv"))
    map_identifiers(rel("citations-raw.csv"), rel("citations-tidy.csv"), rel("id-mapping.csv"))
Exemplo n.º 47
0
def find_dup_via_sort(array):
    """
    :type array: list of int
    :return the smallest duplicates
    """
    sorted_array = merge_sort.merge_sort(array)
    for i in range(len(sorted_array)):
        if i > 0:
            if sorted_array[i - 1] == sorted_array[i]: return sorted_array[i]
    return None
Exemplo n.º 48
0
def test_stability():
    """A."""
    from merge_sort import merge_sort
    lst = [(2, 'ab'), (1, 'ba'), (3, 'ab'), (2, 'ba'), (5, 'ab')]
    one = lst[0]
    two = lst[3]
    sort_lst = merge_sort(lst)
    assert sort_lst == [(1, 'ba'), (2, 'ab'), (2, 'ba'), (3, 'ab'), (5, 'ab')]
    assert sort_lst[1] is one
    assert sort_lst[2] is two
Exemplo n.º 49
0
def test_quick_sort(build_list):
    x, y = build_list
    assert quick_sort(x) == y

    import random
    for i in xrange(100):
        x = [random.randint(10,100) for i in xrange(20)]
        y = merge_sort(x)
        z = quick_sort(x)
        assert y == z
Exemplo n.º 50
0
    def test_randomly(self):

        for each_pass in range(0, 1000):
            random_list = []
            for each_number in range(0, random.randint(3, 40)):
                random_number = random.randint(0, random.randint(1, 1000))
                random_list.append(random_number)
            sorted_random_list = m_s.merge_sort(random_list)
            assert len(random_list) == len(sorted_random_list)
            for each_number in range(0, (len(sorted_random_list) - 1)):
                assert (sorted_random_list[each_number]
                        <= sorted_random_list[(each_number + 1)])
Exemplo n.º 51
0
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()
Exemplo n.º 52
0
def test_input():
    # Checks that it needs a list
    with pytest.raises(TypeError):
        merge_sort()

    d = {1: 'one', 2: 'two'}
    with pytest.raises(TypeError):
        merge_sort(d)

    with pytest.raises(TypeError):
        merge_sort(None)
Exemplo n.º 53
0
def test_merge_sort():
    # get data from file
    print("test merge 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 merge_sort import merge_sort

    out_data = merge_sort(in_data)
    print("out_data", out_data)

    assert (out_data == target_data)
Exemplo n.º 54
0
    def test_predictably(self):

        dict_of_lists = {
            'list_zero': [0, 0, 0, 0, 0, 0, 0, 0],
            'list_one': [0, 0, 0, 0, 1, 1, 1, 1],
            'list_two': [0, 1, 0, 1, 0, 1, 0, 1],
            'list_three': [0, 1, 1, 0, 1, 1, 0, 0],
            'list_four': [10, 100, 1000000, 10000, 1, 100000, 0, 1000],
            'list_five': [0001, 0010, 0100, 1000, 1100, 0011, 0101, 0110],
        }

        for each_key in dict_of_lists:
            each_list = dict_of_lists[each_key]
            sorted_list = m_s.merge_sort(each_list)

            assert len(sorted_list) == len(each_list)

            for each_number in range(0, (len(each_list) - 1)):
                assert (sorted_list[each_number]
                        <= sorted_list[(each_number + 1)])
Exemplo n.º 55
0
        def deterministic_pivot():
            """
            This deterministic method of choosing a pivot is from 1973 by Blum,
            Floyd, Pratt, Rivest, and Tarjan. Outputs 'median of medians' as
            pivot. This is O(n) time despite recursive calls within (!).
            Downsides: it has worse constants in running time than randomized
            pivot and it is not in-place.
            """
            n = right - left + 1
            l = a[left:right+1]

            while len(l) > 5:
                # breaks l into chunks of 5
                l = [l[i:i+5] for i in xrange(0, n, 5)]

                # this is O(n), not O(nlogn), because each chunk is small, constant
                # time for each chunk
                l = [merge_sort(chunk) for chunk in l]
                l = [chunk[len(chunk)/2] for chunk in l]

            median_of_medians = l[len(l)/2]
            return next(i for i,v in enumerate(l) if v == median_of_medians)
Exemplo n.º 56
0
 def test_merge_sort(self):
     self.assertEqual(merge_sort.merge_sort(self._arr), self._res)
Exemplo n.º 57
0
def test_sort_simple():
    """Test on simple case."""
    from merge_sort import merge_sort
    a_list = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
    merge_sort(a_list)
    assert a_list == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Exemplo n.º 58
0
def merge_arrays(array1, array2):
    return merge_sort(merge(array1, array2))
Exemplo n.º 59
0
 def test_merge_sort_correctly_sorts(self):
     sorted_values = merge_sort(self.unsorted_values)
     self.assertEqual(sorted(self.unsorted_values), sorted_values)