def binary_search_array(curr_arr, value, full_arr):
    '''
    :param value: Query value
    :param curr_arr: Input Array that is assumed to be unsorted
    :return: Sorted array and Index of value within array(Index will be based on SORTED output array)
    '''

    # Exit if array is empty
    if len(curr_arr) == 0:
        print("Value not in list")
        return None

    # Heap sort input array
    heap_sort(curr_arr)

    # Size and Middle value
    size = len(curr_arr)
    middle = size // 2

    if curr_arr[middle] == value:
        print("Found value at index :", full_arr.index(value))
        return middle

    # Recursively search right or left children until either value is found or list is empty
    if value < curr_arr[middle]:
        binary_search_array(curr_arr[:middle], value, full_arr)
    elif value > curr_arr[middle]:
        binary_search_array(curr_arr[middle + 1:], value, full_arr)
Ejemplo n.º 2
0
    def array_to_binarytree(self, arr):
        '''
        Use to converted array to Binary Search Tree.
        :param arr: Array of integer elements to pass in
        :return: Node and all right and left (sub)trees
        '''
        # Append only when there is a value assigned and within index of the array
        if len(arr) == 0:
            return None

        # Heap sort input array
        heap_sort(arr)

        # Size, Middle value, and appropriate nodes from current input array
        size = len(arr)
        middle = size // 2
        new_node = Node(arr[middle])

        # Recursively call to append all Left and Right (sub) children
        new_node.left = self.array_to_binarytree(arr[:middle])
        new_node.right = self.array_to_binarytree(arr[middle + 1:])

        # Set the tree's root to arr[middle]
        # Return the current node and it's children
        self.root = new_node
        return new_node
def approach_naive(num):
    container.append(num)
    heap_sort(container)
    n = len(container)
    if n % 2 == 0:
        print((container[n // 2] + container[n // 2 - 1]) / 2)
    else:
        print(container[math.floor(n / 2)])
Ejemplo n.º 4
0
def test_heap_sort():
    for i in range(500):
        array = []

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

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

        assert array == temp
def test_cases():
    # Random Arrays to test
    rand_arr1 = np.random.randint(256, size=8)
    rand_arr2 = np.random.randint(256, size=8)

    # Given Test Cases
    sorted_arr = [0, 1, 2, 3, 4, 5, 7, 9, 10, 12, 14, 18, 20]
    unsorted_arr = [3, 0, 1, 10, 18, 4, 7, 20, 15, 9, 2, 12, 14, 5]

    print(heap_sort(sorted_arr))
    binary_search_array(sorted_arr, 188, sorted_arr)
    binary_search_array(sorted_arr, 188, sorted_arr)

    print(heap_sort(unsorted_arr))
    binary_search_array(unsorted_arr, 4, unsorted_arr)
Ejemplo n.º 6
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))
Ejemplo n.º 7
0
 def test_heap_sort(self):
     """
     Test that it can sort a list of numbers with the heap algorithm.
     """
     data = [4, 78, 2, 33, 0, 99, 86, 4, 21, 3]
     expected = [0, 2, 3, 4, 4, 21, 33, 78, 86, 99]
     output = heap_sort(data)
     self.assertEqual(output, expected)
Ejemplo n.º 8
0
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 search_heuristic(init_state, set_of_operation):
    open_list = []
    relation = {}
    open_list.append(init_state)
    while 1:
        if open_list == []:  # 判断open表是否为空
            print("失败!open表为空,不存在可用节点,无解。")
            return
        vertex = open_list[0]
        open_list = open_list[1:-1]  # 更新open表
        if vertex == [0, 0, 1]:
            result = []  # 存储整个路径
            result.append(vertex)
            res = []  # 存储路径中的单个节点
            print("渡河成功!路径为:")
            while res != init_state:
                res = relation[str(result[-1])]
                if res:
                    result.append(res)
                else:
                    break
            for i in result[::-1]:
                if i != result[0]:
                    print(i, '->', end='')
                else:
                    print(i)
            return
        else:
            if vertex != init_state:
                sons = whether_expandable(vertex, set_of_operation,
                                          relation[str(vertex)])
            else:
                sons = whether_expandable(vertex, set_of_operation, [0, 0, 0])
            if sons:  # 判断当前节点是否可扩展
                sort_list = []
                for i in sons:
                    relation[str(i)] = vertex  # 用字典存储节点间的亲属关系,子节点为键,父节点为值
                    i.append(get_d(i, init_state, relation) +
                             get_w(i))  # 使用启发函数对生成的子节点进行标注,并将标注的权值加到子节点列表内
                    sort_list.append(i)
                heap_sort(sort_list)
                for i in sort_list:
                    i = i[:-1]
                    open_list.append(i)
Ejemplo n.º 10
0
 def test_heap_sort_3(self):
     lst = [
         84, 69, 61, 63, 48, 23, 51, 44, 52, 37, 23, 7, 5, 24, 18, 32, 8,
         17, 48, 36
     ]
     exp = [
         5, 7, 8, 17, 18, 23, 23, 24, 32, 36, 37, 44, 48, 48, 51, 52, 61,
         63, 69, 84
     ]
     self.assertEqual(heap_sort.heap_sort(lst), exp)
Ejemplo n.º 11
0
def merge_sort_composite(arr, left, right):
    if right - left <= 1:
        return
    if right - left <= 1024:
        arr[left:right] = heap_sort(arr[left:right])
        return
    center = left + (right - left) // 2
    merge_sort_composite(arr, left, center)
    merge_sort_composite(arr, center, right)
    merge(arr, left, center, right)
Ejemplo n.º 12
0
 def test_heap_sort_4(self):
     lst = [
         216, 435, 238, 766, 116, 225, 243, 637, 479, 983, 851, 846, 906,
         629, 120, 960, 573, 381, 361, 949, 599, 168, 997, 487, 669, 565,
         667, 635, 27, 269, 642, 81, 14, 988, 108, 418, 625, 821, 166, 592,
         530, 686, 850, 664, 719, 465, 236, 709, 510, 449, 971, 664, 994,
         670, 410, 550, 501, 61, 37, 810, 332, 324, 39, 30, 485, 318, 611,
         546, 398, 852, 71, 904, 887, 540, 402, 985, 265, 859, 76, 265, 772,
         592, 819, 859, 359, 140, 990, 217, 850, 11, 198, 807, 780, 488,
         410, 328, 521, 697, 364, 778
     ]
     self.assertEqual(heap_sort.heap_sort(lst), sorted(lst))
Ejemplo n.º 13
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()
Ejemplo n.º 14
0
def tester():
    fle = open("test_results", 'w')
    for i in range(20):
        testing_lst = [
            randrange(
                1,
                (100) -
                1) for x in range(
                randrange(
                    1,
                    200000))]
        res = heap_sort(testing_lst)
        other_res = sorted(testing_lst)
        if res != other_res:
            # fle.write(str(testing_lst))
            # fle.write('\n')
            print(testing_lst)

        fle.close()
Ejemplo n.º 15
0
def merge_sort_composite_out(file, left, right):
    if right - left <= 1:
        return
    if right - left <= 1024:
        arr = []
        with open(file, 'r+b') as f:
            f.seek(left, 0)
            for i in range(right - left):
                num = f.read(2)
                arr.append(num)
        arr = heap_sort(arr)
        with open(file, 'r+b') as f:
            f.seek(left, 0)
            for i in range(right - left):
                f.write(arr[i])
        return
    center = left + (right - left) // 2
    merge_sort_composite_out(file, left, center)
    merge_sort_composite_out(file, center, right)
    merge_out(file, left, center, right)
Ejemplo n.º 16
0
def sort1(source):
    return heap_sort(source)
 def test_sorted(self):
     self.assertEqual(heap_sort([2, 4, 7]), [2, 4, 7])
Ejemplo n.º 18
0

def gen_a_big_list():

    alist = [randint(0, 1000) for x in range(0, 10000)]

    return alist


if __name__ == '__main__':

    iList = gen_a_big_list()

    #start = time.time()
    quick_sort(iList)
    #end = time.time()

    #print("Quick Sort Calculation time: {}".format(end-start))

    #start = time.time()
    merge_sort(iList)
    #end = time.time()

    #print("Merge Sort Calculation time: {}".format(end-start))

    #start = time.time()
    heap_sort(iList)
    #end = time.time()

    #print("Heap Sort Calculation time: {}".format(end-start))
Ejemplo n.º 19
0
 def test_heap_sort_2(self):
     self.case_name = inspect.currentframe().f_code.co_name
     lst = create_random_int_list(10000, 10)
     exp = sorted(lst)
     self.assertEqual(heap_sort.heap_sort(lst), exp)
Ejemplo n.º 20
0
 def test_heap_sort_sorted(self):
     self.assertTrue(is_sorted(heap_sort(create_sorted(10000))))
Ejemplo n.º 21
0
from heap_sort import heap_sort
import sys
import timeit


def load_file(f):
    file_reader = open(f, 'r')
    s = file_reader.readline()
    str_array = s.split()
    return list(map(int, str_array))


if __name__ == "__main__":
    print_nums = False
    if len(sys.argv) > 1:
        if sys.argv[1] == "--print":
            print_nums = True
    ip_list = load_file("random_files/test-file1000000.txt")
    n = len(ip_list)
    print("Length of list: " + str(n))
    if print_nums:
        print("List before sorting: " + str(ip_list))
    start = timeit.default_timer()
    heap_sort(ip_list)
    stop = timeit.default_timer()
    if print_nums:
        print("List after sorting: " + str(ip_list))
    print("Runtime: " + str(stop - start))
Ejemplo n.º 22
0
from bubble_sort import bubble_sort
from heap_sort import heap_sort
from insertion_sort import insertion_sort

if __name__ == '__main__':

    arr = [3, 5, 2, 4, 1, 6]

    arr_for_ss = copy.deepcopy(arr)
    selection_sort(arr_for_ss)
    print(f'selection_sort: {arr_for_ss}')

    arr_for_qs = copy.deepcopy(arr)
    arr_for_qs = quick_sort(arr_for_qs)
    print(f'quick_sort    : {arr_for_qs}')

    arr_for_ms = copy.deepcopy(arr)
    arr_for_ms = merge_sort(arr_for_ms)
    print(f'merge_sort    : {arr_for_ms}')

    arr_for_bs = copy.deepcopy(arr)
    arr_for_bs = bubble_sort(arr_for_bs)
    print(f'bubble_sort   : {arr_for_bs}')

    arr_for_hs = copy.deepcopy(arr)
    arr_for_hs = heap_sort(arr_for_hs)
    print(f'heap_sort     : {arr_for_hs}')

    arr_for_is = copy.deepcopy(arr)
    arr_for_is = insertion_sort(arr_for_is)
    print(f'insertion_sort: {arr_for_is}')
 def test_unsorted(self):
     self.assertEqual(heap_sort([8, 4, 5, 1, 6]), [1, 4, 5, 6, 8])
Ejemplo n.º 24
0
    bars = None
    generator = None
    B = [0 for x in range(N)]

    if algo == 'quick':
        generator = quicksort(A, 0, len(A) - 1)
        bars = ax.bar(range(len(A)), A, align='edge', color='red')
    elif algo == 'randomized_quick':
        generator = randomized_quicksort(A, 0, len(A) - 1)
        bars = ax.bar(range(len(A)), A, align='edge', color='orange')
    elif algo == 'merge':
        generator = merge_sort(A, 0, len(A) - 1)
        bars = ax.bar(range(len(A)), A, align='edge', color='magenta')
    elif algo == 'heap':
        generator = heap_sort(A)
        bars = ax.bar(range(len(A)), A, align='edge', color='yellow')
    elif algo == 'bubble':
        generator = bubble_sort(A)
        bars = ax.bar(range(len(A)), A, align='edge', color='cyan')
    elif algo == 'insertion':
        generator = insertion(A)
        bars = ax.bar(range(len(A)), A, align='edge', color='black')
    elif algo == 'bucket':
        generator = bucket_sort(A)
        bars = ax.bar(range(len(A)), A, align='edge', color='brown')
    elif algo == 'counting':
        generator = counting_sort(A, B, N + 1)
        bars = ax.bar(range(len(B)), B, align='edge', color='grey')

    title = algo.replace('_', ' ').title()
 def test_unsorted_with_duplication(self):
     self.assertEqual(heap_sort([7, 1, 3, 3, 8, 3, 4, 1]),
                      [1, 1, 3, 3, 3, 4, 7, 8])
Ejemplo n.º 26
0
def handle_updates(updates):
    # andando no json para para chegar no text enviado
    for update in updates["result"]:
        if 'message' in update:
            message = update['message']
        elif 'edited_message' in update:
            message = update['edited_message']
        else:
            print('Can\'t process! {}'.format(update))
            # pega o valor da mensagem mandada para o bot e a quebra
            return
        command = message["text"].split(" ", 1)[0]
        print(command)
        msg = ''
        chat = message["chat"]["id"]

        if len(message["text"].split(" ", 1)) > 1 and len(
                message["text"].split(" ")) == 3:
            try:
                msg = message["text"].split(" ", 1)[1].strip()
                positions = msg.split(" ")[0].strip()
                number = msg.split(" ")[1].strip()
            except:
                return send_message(
                    'Somente um argumento foi passado para o calculo da busca',
                    chat)
        elif (len(message["text"].split(" ")) == 2):
            msg = message["text"].split(" ", 1)[1].strip()
            print(msg)

        if command == '/Buscas':
            send_message(
                "*-------> Busca Sequencial Simples(BSS)*\n*-------> Busca Sequencial Com Sentinela(BSCS)*\n*-------> Busca Sequencial Indexada(BSI)*\n*-------> Busca Binária(BB)*\n*-------> Busca Por Salto(BPS)**\n*-------> Busca Por Interpolaçao(BPS)*",
                chat)
            send_message(
                " Digite '/' a sigla entre parentêses da busca \n ex:*/BSS* (Busca Sequencial Simples)",
                chat)
            send_message(
                " Caso queira comparar uma busca com a outra basta inserir um @ entre as buscas,por exemplo",
                chat)
        elif command == '/BSS':
            search(simple_sequence_search, positions, number,
                   'Busca Sequencial Simples', chat)

            # print('telegram')
        elif command == '/BSCS':
            try:
                search(sentry_sequence_search, positions, number,
                       'Busca Sequencial Com Sentinela', chat)

            except:
                send_message('argumentos inválidos', chat)
        elif command == '/BB':
            try:
                search(binary_search, positions, number, 'Busca Binária', chat)

            except:
                send_message('argumentos inválidos', chat)
        elif command == '/BPS':
            try:

                search(jump_search, positions, number, 'Busca por Salto', chat)

            except:
                send_message('argumentos inválidos', chat)

        elif command == '/BPI':
            try:
                search(interpolation_search, positions, number,
                       'Busca por Interpolação', chat)

            except:
                send_message('argumentos inválidos', chat)

        elif command == '/BSS@BSCS' or command == '/BSCS@BSS':
            try:
                b = command
                b_n = b.replace("@", " ")
                b_new = b_n.replace("/", " ")
                search_list = b_new.split()
                list_names = print_search(search_list)
                list_identify = identify(search_list)

                first_time = compare_search(list_identify[0], positions,
                                            number, list_names[0], chat)
                second_time = compare_search(list_identify[1], positions,
                                             number, list_names[1], chat)
                compare_graph(first_time, second_time)
                bot.send_photo(chat_id=chat,
                               photo=open('./compare_methods.png', 'rb'))
                if first_time > second_time:
                    eficiencia = (first_time / second_time)
                    send_message(
                        'A {} foi {} vezes mais rápida que a {}'.format(
                            list_names[1], int(eficiencia), list_names[0]),
                        chat)
                elif first_time < second_time:
                    eficiencia = (second_time / first_time)
                    send_message(
                        'A {} foi {} vezes mais rápida que a {}'.format(
                            list_names[0], int(eficiencia), list_names[1]),
                        chat)
            except:
                return send_message(
                    'OPS.... algum argumento foi passado errado,tente novamente',
                    chat)

        elif command == '/BSS@BB' or command == '/BB@BSS':
            try:
                b = command
                b_n = b.replace("@", " ")
                b_new = b_n.replace("/", " ")
                search_list = b_new.split()
                list_names = print_search(search_list)
                list_identify = identify(search_list)

                first_time = compare_search(list_identify[0], positions,
                                            number, list_names[0], chat)
                second_time = compare_search(list_identify[1], positions,
                                             number, list_names[1], chat)
                compare_graph(first_time, second_time)
                bot.send_photo(chat_id=chat,
                               photo=open('./compare_methods.png', 'rb'))
                if first_time > second_time:
                    eficiencia = (first_time / second_time)
                    send_message(
                        'A {} foi {} vezes mais rápida que a {}'.format(
                            list_names[1], int(eficiencia), list_names[0]),
                        chat)
                elif first_time < second_time:
                    eficiencia = (second_time / first_time)
                    send_message(
                        'A {} foi {} vezes mais rápida que a {}'.format(
                            list_names[0], int(eficiencia), list_names[1]),
                        chat)
            except:
                return send_message(
                    'OPS.... algum argumento foi passado errado,tente novamente',
                    chat)
            # print("passa")

        elif command == '/BSS@BPI' or command == '/BPI@BSS':
            try:
                b = command
                b_n = b.replace("@", " ")
                b_new = b_n.replace("/", " ")
                search_list = b_new.split()
                list_names = print_search(search_list)
                list_identify = identify(search_list)

                first_time = compare_search(list_identify[0], positions,
                                            number, list_names[0], chat)
                second_time = compare_search(list_identify[1], positions,
                                             number, list_names[1], chat)
                compare_graph(first_time, second_time)
                bot.send_photo(chat_id=chat,
                               photo=open('./compare_methods.png', 'rb'))
                if first_time > second_time:
                    eficiencia = (first_time / second_time)
                    send_message(
                        'A {} foi {} vezes mais rápida que a {}'.format(
                            list_names[1], int(eficiencia), list_names[0]),
                        chat)
                elif first_time < second_time:
                    eficiencia = (second_time / first_time)
                    send_message(
                        'A {} foi {} vezes mais rápida que a {}'.format(
                            list_names[0], int(eficiencia), list_names[1]),
                        chat)
            except:
                return send_message(
                    'OPS.... algum argumento foi passado errado,tente novamente',
                    chat)
            # print("passa")

        elif command == '/BSS@BPS' or command == '/BPS@BSS':
            try:
                b = command
                b_n = b.replace("@", " ")
                b_new = b_n.replace("/", " ")
                search_list = b_new.split()
                list_names = print_search(search_list)
                list_identify = identify(search_list)

                first_time = search(list_identify[0], positions, number,
                                    list_names[0], chat)
                second_time = search(list_identify[1], positions, number,
                                     list_names[1], chat)
                compare_graph(first_time, second_time)
                bot.send_photo(chat_id=chat,
                               photo=open('./compare_methods.png', 'rb'))
                if first_time > second_time:
                    eficiencia = (first_time / second_time)
                    send_message(
                        'A {} foi {} vezes mais rápida que a {}'.format(
                            list_names[1], int(eficiencia), list_names[0]),
                        chat)
                elif first_time < second_time:
                    eficiencia = (second_time / first_time)
                    send_message(
                        'A {} foi {} vezes mais rápida que a {}'.format(
                            list_names[0], int(eficiencia), list_names[1]),
                        chat)
            except:
                return send_message(
                    'OPS.... algum argumento foi passado errado,tente novamente',
                    chat)
            # print("passa")

        elif command == '/BSCS@BB' or command == '/BB@BSCS':
            try:
                b = command
                b_n = b.replace("@", " ")
                b_new = b_n.replace("/", " ")
                search_list = b_new.split()
                list_names = print_search(search_list)
                list_identify = identify(search_list)

                first_time = compare_search(list_identify[0], positions,
                                            number, list_names[0], chat)
                second_time = compare_search(list_identify[1], positions,
                                             number, list_names[1], chat)
                compare_graph(first_time, second_time)
                bot.send_photo(chat_id=chat,
                               photo=open('./compare_methods.png', 'rb'))
                if first_time > second_time:
                    eficiencia = (first_time / second_time)
                    send_message(
                        'A {} foi {} vezes mais rápida que a {}'.format(
                            list_names[1], int(eficiencia), list_names[0]),
                        chat)
                elif first_time < second_time:
                    eficiencia = (second_time / first_time)
                    send_message(
                        'A {} foi {} vezes mais rápida que a {}'.format(
                            list_names[0], int(eficiencia), list_names[1]),
                        chat)
            except:
                return send_message(
                    'OPS.... algum argumento foi passado errado,tente novamente',
                    chat)
            # print("passa")

        elif command == '/BSCS@BPS' or command == '/BPS@BSCS':
            try:
                b = command
                b_n = b.replace("@", " ")
                b_new = b_n.replace("/", " ")
                search_list = b_new.split()
                list_names = print_search(search_list)
                list_identify = identify(search_list)

                first_time = compare_search(list_identify[0], positions,
                                            number, list_names[0], chat)
                second_time = compare_search(list_identify[1], positions,
                                             number, list_names[1], chat)
                compare_graph(first_time, second_time)
                bot.send_photo(chat_id=chat,
                               photo=open('./compare_methods.png', 'rb'))
                if first_time > second_time:
                    eficiencia = (first_time / second_time)
                    send_message(
                        'A {} foi {} vezes mais rápida que a {}'.format(
                            list_names[1], int(eficiencia), list_names[0]),
                        chat)
                elif first_time < second_time:
                    eficiencia = (second_time / first_time)
                    send_message(
                        'A {} foi {} vezes mais rápida que a {}'.format(
                            list_names[0], int(eficiencia), list_names[1]),
                        chat)
            except:
                return send_message(
                    'OPS.... algum argumento foi passado errado,tente novamente',
                    chat)
            # print("passa")

        elif command == '/BSCS@BPI' or command == '/BPI@BSCS':
            try:
                b = command
                b_n = b.replace("@", " ")
                b_new = b_n.replace("/", " ")
                search_list = b_new.split()
                list_names = print_search(search_list)
                list_identify = identify(search_list)

                first_time = compare_search(list_identify[0], positions,
                                            number, list_names[0], chat)
                second_time = compare_search(list_identify[1], positions,
                                             number, list_names[1], chat)
                compare_graph(first_time, second_time)
                bot.send_photo(chat_id=chat,
                               photo=open('./compare_methods.png', 'rb'))
                if first_time > second_time:
                    eficiencia = (first_time / second_time)
                    send_message(
                        'A {} foi {} vezes mais rápida que a {}'.format(
                            list_names[1], int(eficiencia), list_names[0]),
                        chat)
                elif first_time < second_time:
                    eficiencia = (second_time / first_time)
                    send_message(
                        'A {} foi {} vezes mais rápida que a {}'.format(
                            list_names[0], int(eficiencia), list_names[1]),
                        chat)
            except:
                return send_message(
                    'OPS.... algum argumento foi passado errado,tente novamente',
                    chat)
            # print("passa")

        elif command == '/BB@BPI' or command == '/BPI@BB':
            try:
                b = command
                b_n = b.replace("@", " ")
                b_new = b_n.replace("/", " ")
                search_list = b_new.split()
                list_names = print_search(search_list)
                list_identify = identify(search_list)

                first_time = compare_search(list_identify[0], positions,
                                            number, list_names[0], chat)
                second_time = compare_search(list_identify[1], positions,
                                             number, list_names[1], chat)
                compare_graph(first_time, second_time)
                bot.send_photo(chat_id=chat,
                               photo=open('./compare_methods.png', 'rb'))
                if first_time > second_time:
                    eficiencia = (first_time / second_time)
                    send_message(
                        'A {} foi {} vezes mais rápida que a {}'.format(
                            list_names[1], int(eficiencia), list_names[0]),
                        chat)
                elif first_time < second_time:
                    eficiencia = (second_time / first_time)
                    send_message(
                        'A {} foi {} vezes mais rápida que a {}'.format(
                            list_names[0], int(eficiencia), list_names[1]),
                        chat)
            except:
                return send_message(
                    'OPS.... algum argumento foi passado errado,tente novamente',
                    chat)
            # print("passa")

        elif command == '/BB@BPS' or command == '/BPS@BB':
            try:
                b = command
                b_n = b.replace("@", " ")
                b_new = b_n.replace("/", " ")
                search_list = b_new.split()
                list_names = print_search(search_list)
                list_identify = identify(search_list)

                first_time = compare_search(list_identify[0], positions,
                                            number, list_names[0], chat)
                second_time = compare_search(list_identify[1], positions,
                                             number, list_names[1], chat)
                compare_graph(first_time, second_time)
                bot.send_photo(chat_id=chat,
                               photo=open('./compare_methods.png', 'rb'))
                if first_time > second_time:
                    eficiencia = (first_time / second_time)
                    send_message(
                        'A {} foi {} vezes mais rápida que a {}'.format(
                            list_names[1], int(eficiencia), list_names[0]),
                        chat)
                elif first_time < second_time:
                    eficiencia = (second_time / first_time)
                    send_message(
                        'A {} foi {} vezes mais rápida que a {}'.format(
                            list_names[0], int(eficiencia), list_names[1]),
                        chat)
            except:
                return send_message(
                    'OPS.... algum argumento foi passado errado,tente novamente',
                    chat)
            # print("passa")

        elif command == '/BPS@BPI' or command == '/BPI@BPS':
            try:
                b = command
                b_n = b.replace("@", " ")
                b_new = b_n.replace("/", " ")
                search_list = b_new.split()
                list_names = print_search(search_list)
                list_identify = identify(search_list)

                first_time = compare_search(list_identify[0], positions,
                                            number, list_names[0], chat)
                second_time = compare_search(list_identify[1], positions,
                                             number, list_names[1], chat)
                compare_graph(first_time, second_time)
                bot.send_photo(chat_id=chat,
                               photo=open('./compare_methods.png', 'rb'))
                if first_time > second_time:
                    eficiencia = (first_time / second_time)
                    send_message(
                        'A {} foi {} vezes mais rápida que a {}'.format(
                            list_names[1], int(eficiencia), list_names[0]),
                        chat)
                elif first_time < second_time:
                    eficiencia = (second_time / first_time)
                    send_message(
                        'A {} foi {} vezes mais rápida que a {}'.format(
                            list_names[0], int(eficiencia), list_names[1]),
                        chat)
            except:
                return send_message(
                    'OPS.... algum argumento foi passado errado,tente novamente',
                    chat)
            # print("passa")
        elif command == '/SS':
            shell_sort_gif = 'https://media.giphy.com/media/UtQLqAMr6K7052rPxS/giphy.gif'
            send_message(
                'Criado por Donald Shell em 1959, o método ShellSort é considerado um refinamento do método Insertion Sort.',
                chat)
            send_message(
                'Ao invés de considerar o vetor a ser ordenado como um único segmento, ele divide o vetor em sub-grupos.',
                chat)
            send_message(
                'Geralmente divide-se o tamanho do vetor ao meio e guarda o valor em uma variável h os grupos vão sendo ordenados, decrementando o valor de h até que os saltos sejam de elemento em elemento',
                chat)
            send_message('O gif a seguir ilustra bem o ShellSort', chat)
            sendGif(chat, shell_sort_gif)
            vector = fill_vector_disorder(int(msg))
            before = time.time()
            shell_sort(vector)
            after = time.time()
            total = (after - before) * 1000
            return send_message(
                "O tempo gasto para ordenar o vetor foi: {:6f} mili-segundos".
                format(total), chat)

        elif command == '/QS':
            quick_sort_gif = 'https://media.giphy.com/media/m9R2QuROJ1RkToo6P7/giphy.gif'
            send_message(
                'O QuickSort é um algoritmo que aplica o conceito de dividir e conquistar.',
                chat)
            send_message(
                'Para particionar um vetor, escolhe-se um elemento pivô e move-se todos os valores menores para a esquerda e os maiores para a direita',
                chat)
            send_message(
                'Ordena-se recursivamente os valores menores e os maiores,O gif a seguir ilustra bem o QuickSort',
                chat)
            sendGif(chat, quick_sort_gif)
            vector = fill_vector_disorder(int(msg))
            before = time.time()
            quicksort(vector)
            after = time.time()
            total = (after - before) * 1000
            return send_message(
                "O tempo gasto para ordenar o vetor foi: {:6f} mili-segundos".
                format(total), chat)

        elif command == '/BS':
            insertion_sort_gif = 'https://media.giphy.com/media/lT4aB9tDZU4jkoVXiZ/giphy.gif'
            send_message(
                'O BucketSort é um algoritmo que aplica o conceito de dividir e conquistar.',
                chat)
            send_message(
                'Vamos particionar o vetor em um número finitos de baldes. Cada balde é ordenado individualmente, por diferentes algoritmos ou usando o bucket sort recursivamente',
                chat)
            bot.send_photo(chat_id=chat, photo=open('../bucket.png', 'rb'))
            send_message(
                'É eficiente em dados cujos valores são limitados. Na nossa implementação cada balde foi ordenado usando o método insertion sort. Relembre através desse gif:',
                chat)
            sendGif(chat, insertion_sort_gif)
            vector = fill_vector_disorder(int(msg))
            before = time.time()
            bucket_sort(vector)
            after = time.time()
            total = (after - before) * 1000
            return send_message(
                "O tempo gasto para ordenar o vetor foi: {:6f} mili-segundos".
                format(total), chat)
        elif command == '/HS':
            send_message(
                'Heap Sort é um algoritmo de ordenação popular e eficiente em programação de computadores. Aprender a escrever o ',
                chat)
            time.sleep(3)
            send_message(
                'algoritmo de classificação de pilha requer conhecimento de dois tipos de estruturas de dados - arrays e árvores.',
                chat)
            time.sleep(3)
            send_message(
                'Seu funcionamento é fundamentado na visualização dos elementos do array em uma forma especial,chamada heap.',
                chat)
            time.sleep(3)
            send_message('Entendendo uma árvore binária', chat)
            time.sleep(3)
            send_message(
                'Uma árvore binária é uma estrutura de dados em que cada pai (um nó da árvore) pode ter no máximo dois filhos. ',
                chat)
            time.sleep(4)
            send_message('Na imagem, cada elemento possui 2 filhos ', chat)
            time.sleep(3)
            bot.send_photo(chat_id=chat,
                           photo=open('../imagens/imagem_1.jpg', 'rb'))
            time.sleep(2)
            send_message('Árvore binária cheia', chat)
            time.sleep(2)
            send_message(
                'Uma árvore binária cheia (full binary tree) é um tipo especial de árvore binária,em que todos os pais tem dois filhos ou nenhum.',
                chat)
            time.sleep(2)
            bot.send_photo(chat_id=chat,
                           photo=open('../imagens/imagem_2.jpg', 'rb'))
            time.sleep(2)
            send_message('Árvore binária completa', chat)
            time.sleep(1)
            send_message(
                'Uma árvore binária completa (Complete binary tree) é como uma árvore binária cheia,mas com duas grandes diferenças:',
                chat)
            time.sleep(4)
            send_message(
                '1. Cada nível deve ser completamente preenchido \n 2. Todos os elementos da folha devem inclinar-se para a esquerda.\n 3. O último elemento de folha não pode ter um certo irmão, isto é, uma árvore binária completa não precisa ser uma árvore binária cheia.',
                chat)
            time.sleep(4)
            bot.send_photo(chat_id=chat,
                           photo=open('../imagens/imagem_3.jpg', 'rb'))
            send_message(
                'Como criar uma árvore binária completa de uma lista não-ordenada (array)?',
                chat)
            time.sleep(3)
            send_message(
                '1.Selecione o primeiro elemento da lista para ser o nó raiz. (Primeiro nível - 1 elemento)',
                chat)
            time.sleep(3)
            send_message(
                '2.Coloque o segundo elemento como um filho à esquerda do nó raiz e o terceiro elemento como um filho a direita,2.Coloque o segundo elemento como um filho à esquerda do nó raiz e o terceiro elemento como um filho a direita.',
                chat)
            time.sleep(3)
            send_message(
                '3. Colocar em seguida dois elementos como filhos do nó esquerdo do segundo nível. Mais uma vez,colocar os dois próximos elementos como filhos do nó direito do segundo nível (nível 3 - 4 elementos).',
                chat)
            time.sleep(3)
            send_message('4. Continue repetindo até chegar o último elemento.',
                         chat)
            bot.send_photo(chat_id=chat,
                           photo=open('../imagens/imagem_4.jpg', 'rb'))
            time.sleep(2)
            send_message(
                'Relação entre índices do array e elementos da árvore', chat)
            time.sleep(3)
            send_message(
                'Relação entre índices do array e elementos da árvore', chat)
            time.sleep(3)
            send_message(
                'Árvore binária completa tem uma propriedade interessante que podemos usar para encontrar os filhos e os pais de qualquer nó.',
                chat)
            time.sleep(3)
            send_message(
                'Se o índice de qualquer elemento do array é i, o elemento do índice 2i + 1 vai se tornar a criança esquerda '
                'enquanto que o elemento do índice a direita se dará por 2i + 2. Além disso, o pai de qualquer elemento no '
                'índice é dada pelo limite inferior de (i-1) / 2.', chat)
            time.sleep(5)
            bot.send_photo(chat_id=chat,
                           photo=open('../imagens/imagem_5.jpg', 'rb'))
            time.sleep(3)
            send_message('A estrutura do heap', chat)
            time.sleep(3)
            send_message(
                'Heap é uma estrutura de dados baseados em árvores especiais. Uma árvore binária é dito a seguir '
                'uma estrutura de dados heap se:', chat)
            time.sleep(5)
            send_message('Deve ser uma árvore binária completa.', chat)
            send_message(
                'Todos os nós na árvore seguem a propriedade que eles são superiores a seus filhos, ou seja, '
                'o elemento maior é a raiz e ambos os seus filhos assumem lugar de nós, ligados a elementos menores que a raiz '
                'e assim por diante. Esse processo é um heap chamado max-heap. Se em vez disso, todos os nós são menores do que '
                'seus filhos, é chamado de min-heap.', chat)
            time.sleep(5)
            send_message(
                'A imagem a seguir mostra bem o max-heap e o min-heap', chat)
            bot.send_photo(chat_id=chat,
                           photo=open('../imagens/imagem_6.jpg', 'rb'))
            time.sleep(3)
            send_message('Como fazer o processo de heapify', chat)
            send_message(
                'A partir de uma árvore binária completa, nós podemos modificá-lo para se tornar um Max-Heap, executando uma '
                'função chamada heapify sobre todos os elementos não-folha do heap.',
                chat)
            time.sleep(5)
            send_message(
                'Na imagem executamos o heapify em uma árvore com apenas três elementos.',
                chat)
            bot.send_photo(chat_id=chat,
                           photo=open('../imagens/imagem_7.jpg', 'rb'))
            time.sleep(3)
            send_message(
                'O exemplo acima mostra dois cenários - um em que a raiz é o elemento maior e não precisamos fazer nada.'
                'E outra na qual raiz tinha o maior elemento como um filho e precisava trocar para manter a propriedade de '
                'max-heap.', chat)
            time.sleep(5)
            send_message(
                'Agora vamos pensar em outro cenário a partir da imagem a seguir',
                chat)
            bot.send_photo(chat_id=chat,
                           photo=open('../imagens/imagem_8.jpg', 'rb'))
            time.sleep(3)
            send_message(
                'O elemento superior não é um max-heap, mas todas as sub-árvores são max-heaps.',
                chat)
            send_message(
                'Para manter a propriedade de max-heap para a árvore inteira, temos que continuar puxando 2 posições para '
                'baixo até que ele atinja sua posição correta.', chat)
            time.sleep(4)
            bot.send_photo(chat_id=chat,
                           photo=open('../imagens/imagem_9.jpg', 'rb'))
            time.sleep(3)
            send_message(
                'Assim, para manter a propriedade de max-heap em uma árvore, onde ambas as sub-árvores são max-heaps, '
                'precisamos executar o heapify no elemento raiz, repetidamente, até que o mesmo seja maior do que seus '
                'filhos ou se torne um nó folha.', chat)
            time.sleep(6)
            send_message('Construindo o max-heap', chat)
            send_message(
                'Para construir um max-heap de qualquer árvore, podemos começar aplicar o processo de heapify para cada '
                'sub-árvore de baixo a cima e finalizar com um max-heap depois que a função é aplicada em todos os elementos, '
                'incluindo o elemento raiz.', chat)
            time.sleep(6)
            send_message(
                'No caso de uma árvore completa, o primeiro índice do nó não-folha é dada por n/2 - 1.'
                ' Todos os outros nós depois que são nós de folha não precisam passar pelo heapify.',
                chat)
            time.sleep(3)
            send_message(
                'A imagem a seguir representa a construção do max-heap', chat)
            bot.send_photo(chat_id=chat,
                           photo=open('../imagens/imagem_10.jpg', 'rb'))
            time.sleep(3)
            send_message(
                'Como mostra no diagrama acima, começamos por heapifying as árvores das menores para os mais baixas e '
                'mover-las gradualmente até chegarmos ao elemento raiz.', chat)
            send_message('Enfim, o heap sort', chat)
            send_message('Etapas para execução do heap sort:', chat)
            send_message(
                '1. Desde que a árvore satisfaça a propriedade de Max-Heap, então, o maior item é armazenado no nó raiz.',
                chat)
            send_message(
                '2. Remover o elemento raiz e colocar no final do array (n-ésima posição. Colocar o último item da árvore (heap) '
                'no lugar vago.', chat)
            send_message(
                '3. Reduzir o tamanho do heap por 1 e aplicar o heapify no elemento raiz novamente para que possamos ter '
                'o maior elemento como raiz.', chat)
            send_message(
                '4. O processo é repetido até que todos os itens da lista é classificada.',
                chat)
            bot.send_photo(chat_id=chat,
                           photo=open('../imagens/imagem_11.jpg', 'rb'))
            send_message(
                'Depois dessa explicação,executaremos o HeapSort para você ver o tempo que demora para a ordenação por completa do vetor',
                chat)
            arr = fill_vector_disorder(int(msg))
            before = time.time()
            heap_sort(arr)
            after = time.time()
            total = (after - before) * 1000  # Segundos multiplicados em 10000
            return send_message(
                "O tempo gasto para ordenar o vetor foi: {:6f} mili-segundos".
                format(total), chat)
Ejemplo n.º 27
0
 def test_heap_sort_1(self):
     lst = [21, 15, 10, 8, 5]
     exp = [5, 8, 10, 15, 21]
     self.assertEqual(heap_sort.heap_sort(lst), exp)
Ejemplo n.º 28
0
 def test_heap_sort_6(self):
     lst = create_random_int_list(1000, 10)
     self.assertEqual(heap_sort.heap_sort(lst), sorted(lst))
 def test_one(self):
     self.assertEqual(heap_sort([1]), [1])
 def test_can_it_work(self):
     self.test_array = range(0,11,1)
     sorted_array = heap_sort.heap_sort(self.test_array)
     self.assertEqual(sorted_array,range(10,-1,-1))
Ejemplo n.º 31
0
 def test_heap_sort_correctly_sorts(self):
     sorted_values = heap_sort(self.unsorted_values)
     self.assertEqual(sorted(self.unsorted_values), sorted_values)
Ejemplo n.º 32
0
 def test_heap_sort_should_sort_a_list(self):
     self.assertEqual([1, 2, 3, 4, 5], heap_sort([4, 2, 3, 5, 1]))
Ejemplo n.º 33
0
 def test_heap_sort_does_not_mutate_input(self):
     values = list(self.unsorted_values)
     sorted_values = heap_sort(self.unsorted_values)
     self.assertEqual(self.unsorted_values, values)
Ejemplo n.º 34
0
print('Bubble Sort: ' + str(bubble_sort(lst)))

lst = generate_random_list(100)

print('Selection Sort: ' + str(selection_sort(lst)))

lst = generate_random_list(100)

print('Insertion Sort: ' + str(insertion_sort(lst)))

lst = generate_random_list(100)

print('Merge Sort: ' + str(merge_sort(lst)))

lst = generate_random_list(100)

print('Quick Sort: ' + str(quick_sort(lst)))

lst = generate_random_list(100)

print('Heap Sort: ' + str(heap_sort(lst)))

lst = generate_random_list(100)

print('Counting Sort: ' + str(counting_sort(lst)))

lst = generate_random_list(100)

print('Radix Sort: ' + str(radix_sort(lst)))
Ejemplo n.º 35
0
        1.冒泡排序  2.快速排序
        3.插入排序  4.选择排序
        5.堆排序    6.归并排序
        ''')

        sel = input()
        start = time.time()  #计算运行时间
        if (sel == '1'):
            print(bubble_sort.bubble_sort(listin))
        elif (sel == '2'):
            deallist = listin[:]
            quick_sort.quick_sort(deallist, 0, len(deallist) - 1)
            print(deallist)
        elif (sel == '3'):
            print(insertion_sort.insertion_sort(listin))
        elif (sel == '4'):
            print(selection_sort.selection_sort(listin))
        elif (sel == '5'):
            print(heap_sort.heap_sort(listin))
        elif (sel == '6'):
            deallist = listin[:]
            print(merge_sort.merge_sort(deallist))
        else:
            raise ValueError
        end = time.time()
        print('程序运行时间:%f ns' % ((end - start) * 1000000))
        print('输入Q/q退出,或继续尝试其他算法')
        if input().lower() == 'q':
            exit(0)
except ValueError:
    print('请输入正确的值!')
Ejemplo n.º 36
0
 def test_heap_sort(self):
     result = heap_sort(self.arr)
     self.assertEqual(result, self.answer)
Ejemplo n.º 37
0
 def test_heap_sort_returns_an_array(self):
     sorted_values = heap_sort(self.unsorted_values)
     assert isinstance(sorted_values, list)
Ejemplo n.º 38
0
 def test_heap_sort_for_a_huge_input(self):
     expected = self.test_kit.huge_set_of_n()
     input_nums = self.test_kit.huge_sample_of_n()
     actual = heap_sort(input_nums)
     self.assertListEqual(expected, actual)
Ejemplo n.º 39
0
 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, heap_sort(items))
Ejemplo n.º 40
0
 def test_heap_sort(self):
     self.assertEqual(heap_sort.heap_sort(self._arr), self._res)
Ejemplo n.º 41
0
 def test_heap_sort_2(self):
     lst = [8, 5, 4, 3, 2, 3, 0, 1, 3, 2]
     exp = [0, 1, 2, 2, 3, 3, 3, 4, 5, 8]
     self.assertEqual(heap_sort.heap_sort(lst), exp)