def test_merge_sort():
    assert merge_sort([]) == []
    assert merge_sort([2]) == [2]
    assert merge_sort([3, 5, 6, 7, 4, 2]) == [2, 3, 4, 5, 6, 7]
    assert merge_sort([7, 4, 5, 3, 2, 6]) == [2, 3, 4, 5, 6, 7]
    assert merge_sort([3, 7, 9, 1, 5, 7, 8,
                       2]) == sorted([3, 7, 9, 1, 5, 7, 8, 2])
Ejemplo n.º 2
0
def test_merge_sort_strings():
    assert merge_sort([
        "C59OK", "5QV09", "TCNId", "ne58v", "ges28", "EzMbM", "qdPku", "ltinw",
        "Nt1Rj", "nSb8R"
    ]) == [
        "5QV09", "C59OK", "EzMbM", "Nt1Rj", "TCNId", "ges28", "ltinw", "nSb8R",
        "ne58v", "qdPku"
    ]
Ejemplo n.º 3
0
    def sort(self):
        self.draw_bars()
        self.display_sorttext()
        if self.algorithm == 'bubble':
            algorithms.bubble_sort(self)

        if self.algorithm == 'insertion':
            algorithms.insertion_sort(self)

        if self.algorithm == 'quick':
            algorithms.quick_sort(self, isfirst_call = True)
            if algorithms.stop_recursive_sort == False:
                self.issorted = True

        if self.algorithm == 'merge':
            algorithms.merge_sort(self, isfirst_call = True)
            if algorithms.stop_recursive_sort == False:
                self.issorted = True

        if self.algorithm == 'heap':
            algorithms.heap_sort(self)
            if algorithms.stop_recursive_sort == False:
                self.issorted = True
Ejemplo n.º 4
0
def startAlgorithm():
    global data
    tick = speedScale.get()
    if select_alg.get() == "Bubble sort":
        sorted_data = bubble_sort(data, draw_data, tick)
        print(sorted_data)
        canvas.delete("all")
        draw_data(sorted_data, ["white" for x in range(len(data))])

    elif select_alg.get() == "Insertion Sort":
        sorted_data = insertion_sort(data, draw_data, tick)
        print(sorted_data)
        canvas.delete("all")
        draw_data(sorted_data, ["white" for x in range(len(data))])

    elif select_alg.get() == "Selection Sort":
        sorted_data = selection_sort(data, draw_data, tick)
        print(sorted_data, )
        canvas.delete("all")
        draw_data(sorted_data, ["white" for x in range(len(data))])

    elif select_alg.get() == "Heap Sort":
        sorted_data = heap_sort(data, draw_data, tick)
        print(sorted_data, )
        canvas.delete("all")
        draw_data(sorted_data, ["white" for x in range(len(data))])

    elif select_alg.get() == "Quick Sort":
        sorted_data = quick_sort(data, draw_data, tick)
        print(sorted_data, )
        canvas.delete("all")
        draw_data(sorted_data, ["white" for x in range(len(data))])

    elif select_alg.get() == "Merge Sort":
        sorted_data = merge_sort(data, draw_data, tick)
        print(sorted_data, )
        canvas.delete("all")
        draw_data(sorted_data, ["white" for x in range(len(data))])
Ejemplo n.º 5
0
            )


############################################

print("How many integers would you like sorted?: ")

array_length = inputNumber(1, 2**64)
array = random.sample(range(1, array_length), k=array_length - 1)

algorithm_data = {
    1: ("Selection Sort", selection_sort(array)),
    2: ("Bubble Sort", bubble_sort(array)),
    3: ("Insertion Sort", insertion_sort(array)),
    4: ("Shell Sort", shell_sort(array)),
    5: ("Merge Sort", merge_sort(array)),
    6: ("Quick Sort", quick_sort(array, 0,
                                 len(array) - 1)),
    7: ("Heap Sort", heap_sort(array))
}
print("Welcome to Urmzd's Sorting Algorithm Visualizer: ")
print("Select one of the following sorting algorithms: ")

for k, v in algorithm_data.items():
    print(f"Type {k} for {v[0]}")

algorithm_number = inputNumber(1, 7)

algorithm_name, algorithm = algorithm_data.get(algorithm_number)

counter = [0]
Ejemplo n.º 6
0
import algorithms
import file_handler
import os

# CONSTANTS
DIRECTORY = os.path.dirname(__file__)
FILE_PATH = os.path.join(DIRECTORY, "data.txt")
MERGE_OUT_PATH = os.path.join(DIRECTORY, "merge.out")

if __name__ == "__main__":
    data_list = file_handler.read_data_from_file(FILE_PATH)

    for number_list in data_list:
        algorithms.merge_sort(number_list)

    file_handler.write_data_to_file(data_list, MERGE_OUT_PATH)
Ejemplo n.º 7
0
 def call_sort_method(self, random_list, max_vet, j):
     begin = time.time()
     merge_sort(random_list)
     end = time.time()
     print('merge sort with {} items vet[{}]: {} seconds'.format(max_vet, j + 1, end - begin))
     return end - begin
Ejemplo n.º 8
0
 def sortUsingMergeSort(self):
     algorithms.merge_sort(self.bookSortedCatalog)
def test_empty_array(empty_array):
    assert merge_sort(empty_array) == []
Ejemplo n.º 10
0
def test_it_sorts_a_list_of_numbers():
    list_unsorted = [9, 2, 1, 4, 8, 3, 5]
    merge_sort(list_unsorted)

    assert list_unsorted == [1, 2, 3, 4, 5, 8, 9]
Ejemplo n.º 11
0
def test_it_sorts_a_list_of_numbers_with_duplicates():
    list_unsorted = [7, 7, 5, 4, 3, 3, 1]
    merge_sort(list_unsorted)

    assert list_unsorted == [1, 3, 3, 4, 5, 7, 7]
Ejemplo n.º 12
0
def test_it_sorts_a_inverse_sorted_list_of_numbers():
    list_unsorted = [7, 6, 5, 4, 3, 2, 1]
    merge_sort(list_unsorted)

    assert list_unsorted == [1, 2, 3, 4, 5, 6, 7]
Ejemplo n.º 13
0
def test_merge_sort_numbers():
    assert merge_sort(
        [3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50,
         48]) == [2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 44, 46, 47, 48, 50]
def test_descending_array(descending_array):
    assert merge_sort(descending_array) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Ejemplo n.º 15
0
def menu_bookstore_system() :
    bookStore = BookStore.BookStore()
    option=""
    while option != '0':
        print("""
        1 Load book catalog into book Catalog
        2 BFS
        3 DFS
        0 Return to Main Menu
        """)
        '''
        4 Sort bookCatalog using Merge Sort
        5 Sort bookCatalog using Quick Sort
        6 Search by PreFix using Binary Search
        7 Quick Sort Catalog using LinkedList
        8 Merge Sort Catalog using LinkedList
        9 Remove a book by index from catalog
        10 Add a book by index to shopping cart
        11 Remove from the shopping cart
        12 Search book by infix
        13 Print Best Selling Book
        14 Reverse order of shopping cart
        15 Search books by title
        16 Search book by prefix
        17 Save to file using BF traversal
        18 in-order
        19 pre-order
        20 post-order
        21 Search Book by Prefix BestSellers
        r setRandomShoppingCart
        s setShoppingCart
        0 Return to main menu
        '''
        option=input() 
        if option=="r":
            bookStore.setRandomShoppingCart()
        elif option=="s":
            bookStore.setShoppingCart()
        elif option=="1":
            file_name = input("Introduce the name of the file: ")
            bookStore.loadCatalog(file_name)
        elif option =="2":
            index = int(input("Enter the index: "))
            k = int(input("Enter the degree: "))
            #print( bookStore.similarGraph.bfs2(index,k))
            traversal = bookStore.similarGraph.bfs2(index,k)
            for i in range(1, len(traversal)):
                        print(bookStore.bookCatalog.get(traversal[i]))
        elif option =="3":
            print(bookStore.similarGraph.dfs2(int(input("Enter the index: ")),int(input("Enter the index: ")))) 
        elif option =="4":
            print("loading...")
            start_time = time.time()
            algorithms.merge_sort(bookStore.sortedBookCatalog)
            elapsed_time = time.time() - start_time
            print(f"Sort completed in {elapsed_time} seconds")
        elif option =="5":
            print("loading...")
            start_time = time.time()
            algorithms.quick_sort(bookStore.sortedBookCatalog)
            elapsed_time = time.time() - start_time
            print(f"Sort completed in {elapsed_time} seconds")
        elif option =="6":
            bookStore.binarySearchbyTitle(input("Enter a prefix: "))
        elif option =="7":
            print("loading...")
            algorithms.quick_sort(bookStore.sortedBookCatalog)
            print("Sorted")
        elif option =="8":
            print("loading...")
            bookStore.mergeSortedBooksDLList()
            print("Sorted")

        elif option=="9":
            i = int(("Introduce the index to remove from catalog: "))
            bookStore.removeFromCatalog(i)
        elif option=="10":
            i = int(input("Introduce the index to add to shopping cart: "))
            bookStore.addBookByIndex(i)
        elif option=="11":
            bookStore.removeFromShoppingCart()
        elif option=="12":
            infix = input("Introduce the query to search: ")
            bookStore.searchBookByInfix(infix)
        elif option =="13":
            bookStore.bestSellingBook()
        elif option =="14":
            bookStore.reverse()
        elif option =="15":
            t = input("Introduce the query to search: ")
            bookStore.searchBookByTitle(t)
        elif option =="16":
            t = input("Introduce the query to search: ")
            bookStore.searchByPrefix(t)
        elif option =="17":
            print("laoding")
            bookStore.indexSortedTitle.bf_traverse()
            print("Saved to File")
        elif option =="18":
            print("laoding")
            bookStore.indexSortedTitle.in_order(bookStore.indexSortedTitle.r, [])
            print("Saved to File")
        elif option =="19":
            print("laoding")
            bookStore.indexSortedTitle.pre_order(bookStore.indexSortedTitle.r, [])
            print("Saved to File")
        elif option =="20":
            print("laoding")
            bookStore.indexSortedTitle.post_order(bookStore.indexSortedTitle.r, [])
            print("Saved to File")
        elif option =="21":
            bookStore.searchByPrefix(input("Introduce the query to search: "), input("Enter K Size"))
            print("loading...")
        ''' 
def test_merge_sort():
    assert merge_sort(ls1) == sorted(ls1)
    assert merge_sort(ls2) == sorted(ls2)
    assert merge_sort(ls3) == sorted(ls3)
    assert merge_sort(ls4) == sorted(ls4)
    assert merge_sort(ls5) == sorted(ls5)
            # reading information from GUI
            size = int(values[len(values) - 2])
            a = tools.generate_random_list(size)
            sorting_speed = int(105 - values[len(values) - 3])
            if sorting_method == "Selection Sort":
                generator = algorithms.selection_sort(a)
                title = "Selection Sort of {} numbers".format(size)
            elif sorting_method == "Insertion Sort":
                generator = algorithms.insertion_sort(a)
                title = "Insertion Sort of {} numbers".format(size)
            elif sorting_method == "Bubble Sort":
                generator = algorithms.bubble_sort(a)
                title = "Bubble Sort of {} numbers".format(size)
            elif sorting_method == "Merge Sort":
                generator = algorithms.merge_sort(a)
                title = "Merge Sort of {} numbers".format(size)

            # Generating bar graph
            fig, ax = plt.subplots()
            ax.set_title(title)
            bar_rects = ax.bar(range(len(a)), a, align="edge", color="#61b0ff")
            ax.set_xlim(0, size)
            ax.set_ylim(0, 100)
            text = ax.text(0.02, 0.95, "", transform=ax.transAxes)

            iteration = [0]

            def update_fig(A, rects, i):
                """
                Updates the bar graph after each iteration of sort.
Ejemplo n.º 18
0
        print(f'List with {elements} elements:')

        if elements < THRESHOLD_ELEMENTS_SLOW_ALGORITHMS:
            bubble_sort(deepcopy(list_unsorted))
            print(f'Bubble sort: \t\t{bubble_sort.execution_time}')

            selection_sort(deepcopy(list_unsorted))
            print(f'Selection sort: \t{selection_sort.execution_time}')

            insertion_sort(deepcopy(list_unsorted))
            print(f'Insertion sort: \t{insertion_sort.execution_time}')
        else:
            print(
                'Bubble sort: \t\tSkipping algorithm because it takes a long time'
            )
            print(
                'Selection sort: \tSkipping algorithm because it takes a long time'
            )
            print(
                'Insertion sort: \tSkipping algorithm because it takes a long time'
            )

        quick_sort(deepcopy(list_unsorted), 0, len(list_unsorted) - 1)
        print(f'Quick sort: \t\t{quick_sort.execution_time}')

        merge_sort(deepcopy(list_unsorted))
        print(f'Merge sort: \t\t{merge_sort.execution_time}')

        heap_sort(deepcopy(list_unsorted))
        print(f'Heap sort: \t\t{heap_sort.execution_time}\n')
def test_identical_array(identical_array):
    assert merge_sort(identical_array) == [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]