Beispiel #1
0
 def test_insertion_sort(self):
     
     self.assertListEqual(insertion_sort([1,5,3,2,4]), [1,2,3,4,5])
     self.assertListEqual(insertion_sort([8,5,3,2,4]), [2,3,4,5,8])
     self.assertListEqual(insertion_sort([1,5,25,2,4]), [1,2,4,5,25])
     self.assertListEqual(insertion_sort([1,5,9,3,2,4]), [1,2,3,4,5,9])
     self.assertListEqual(insertion_sort([1,5,3,2,100,4]), [1,2,3,4,5,100])
Beispiel #2
0
def start_algorithm():
    """
    Starts the algorithm based on the selection from the user in the ComboBox
    Expected Complexity: dependent on the sort selected
    """

    global data_list

    if algorithm_menu.get() == "Bubble Sort":
        bubble_sort(data_list, draw_data, speed_scale.get())

    elif algorithm_menu.get() == "Selection Sort":
        selection_sort(data_list, draw_data, speed_scale.get())

    elif algorithm_menu.get() == "Insertion Sort":
        insertion_sort(data_list, draw_data, speed_scale.get())

    elif algorithm_menu.get() == "Quick Sort":
        quick_sort(data_list, 0,
                   len(data_list) - 1, draw_data, speed_scale.get())

    elif algorithm_menu.get() == "Merge Sort":
        merge_sort(data_list, 0,
                   len(data_list) - 1, draw_data, speed_scale.get())

    elif algorithm_menu.get() == "Heap Sort":
        heap_sort(data_list, draw_data, speed_scale.get())

    elif algorithm_menu.get() == "Cocktail Sort":
        cocktail_sort(data_list, draw_data, speed_scale.get())
Beispiel #3
0
 def test_insertion_sort(self):
     for x in range(TEST_ARRAYS_COUNT):
         array = [random.randrange(0, 1000) for y in range(x * 100 + 1)]
         unsorted = array.copy()
         unsorted.sort()
         insertion_sort(array)
         self.assertEqual(unsorted, array)
Beispiel #4
0
 def test_insertion_sort_list(self):
     l = List()
     l.append(ListItem("d"))
     l.append(ListItem("a"))
     self.assertEqual(insertion_sort(l).get_items(), ["a", "d"])
     l = List()
     l.append(ListItem("d"))
     l.append(ListItem("a"))
     l.append(ListItem("v"))
     l.append(ListItem("b"))
     l.append(ListItem("z"))
     self.assertEqual(insertion_sort(l).get_items(), ["a", "b", "d", "v", "z"])
Beispiel #5
0
def test_insertion(user_int):
    test_list = [i for i in range(user_int)]
    random.shuffle(test_list)

    start_time = time.time()
    insertion_sort(test_list, 0, len(test_list) - 1)
    final_time = time.time()

    total_time = final_time - start_time
    result_str = generate_results(test_list, total_time, "Insertion")

    print(result_str)

    return None
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())
def main():
    # Test quicksort
    t_list = make_rand_list(10)
    print(t_list)
    print(quicksort(t_list))
    print(mergesort(t_list))
    print(bubblesort(t_list))
    print(insertion_sort(t_list))
Beispiel #8
0
def bucket_sort(array):
    try:
        min_a = min(array)
        max_a = max(array)
        len_a = len(array)
        buckets = [[] for x in range(len_a + 10)]
        for x in array:
            buckets[int(len_a * x / (max_a - min_a))].append(x)
        for b in buckets:
            insertion_sort(b)
        narray = []
        for b in buckets:
            narray += b
        for x in range(len_a):
            array[x] = narray[x]
    except ZeroDivisionError:
        pass
Beispiel #9
0
def test_insertion(user_int):

    # build the test list
    test_list = [i for i in range(user_int)]
    random.shuffle(test_list)

    # time tracking of the sort
    start_time = time.time()
    insertion_sort(test_list, 0, len(test_list) - 1)
    final_time = time.time()

    # generate and print results
    total_time = final_time - start_time
    result_str = generate_results(test_list, total_time, "Insertion")

    print(result_str)

    return None
Beispiel #10
0
def run_sort(n):
    output = [0, 0, 0, 0]

    # Generate strings
    (a, b) = generate_alphanumeric_strings(n, STRING_WIDTH)

    # Insertion sort
    if n <= 1000:
        print("Running insertion sort...")
        insertion_a = a.copy()
        st = time.time()
        insertion_sorted = insertion_sort(insertion_a)
        output[0] = time.time() - st
        print("Sort took a total of %s seconds" % str(time.time() - st))
        verify_sort(insertion_sorted)
        print("\n")
    else:
        print(
            "Insertion sort only runs up to a value of 100000 otherwise it takes too long."
        )
        print("\n")

    # Quick sort
    print("Running quick sort...")
    quick_a = a.copy()
    st = time.time()
    quick_sorted = quick_sort(quick_a, 0, len(quick_a) - 1)
    output[1] = time.time() - st
    print("Sort took a total of %s seconds" % str(time.time() - st))
    verify_sort(quick_sorted)
    print("\n")

    if n <= 1000000:
        # Merge sort
        print("Running merge sort...")
        merge_a = a.copy()
        st = time.time()
        merge_sorted = merge_sort(merge_a)
        output[2] = time.time() - st
        print("Sort took a total of %s seconds" % str(time.time() - st))
        verify_sort(merge_sorted)
        print("\n")

    if n <= 100000:
        # Tree hash sort
        print("Running tree hash sort...")
        hash_a = a.copy()
        st = time.time()
        t = HashTable(values=hash_a, accuracy=ACCURACY)
        t.sort()
        output[3] = time.time() - st
        print("Sort took a total of %s seconds" % str(time.time() - st))
        hash_sorted = t.get_values()
        verify_sort(hash_sorted)
        print("\n")

    return output
Beispiel #11
0
def quick_sort(dll, start, end, size, threshold):
    """
<<<<<<< HEAD
    quick_sort
    :param dll: the dll to sort
    :param start: start of dll to sort
    :param end: end of dll to sort
    :param size: size of dll
    :param threshold: size that if less than or equal to will send dll to insertion sort
    :return: sort dll
=======
    Uses the quick sort algorithm to sort the DLL
    :param dll: [DLL] the dll to sort
    :param start: [DLLNode] start of dll to sort
    :param end: [DLLNode] end of dll to sort
    :param size: [int] size of dll
    :param threshold: [int] size that if less than or equal to will send dll to insertion sort
    :return: [DLL] sort dll
>>>>>>> f39e3b14ac55bc1f92fc152e7e5a0672b52e0cc7
    """
    if threshold >= size > 1:  # could be one idk
        insertion_sort(dll, start, end)
        return
    else:
        if size < 2:
            return
        # returns (pivot node, size from start to pivot)
        tup = partition(start, end)

        if tup[0] is None:
            return

    # Get right hand size, start with 0 because of .get_next() call below
    rhand_size = 0
    val = tup[0]

    # Reset tail if needed
    while dll.get_tail().get_next() is not None and dll.get_tail() is not None:
        dll.set_tail(dll.get_tail().get_next())
        end = dll.get_tail()
Beispiel #12
0
    def test_insertion(self):
        dll = DLL([])

        assert dll.get_size() == 0
        assert dll.get_head() is None
        assert dll.get_tail() is None

        # normal
        orig = [6, 1, 4, 7, 3, 5, 10, 8, 9, 2]
        dll = DLL(orig)
        insertion_sort(dll, dll.get_head(), dll.get_tail())
        assert dll == DLL(sorted(orig))

        # size 1
        orig = [6]
        dll = DLL(orig)
        insertion_sort(dll, dll.get_head(), dll.get_tail())
        assert dll == DLL(sorted(orig))

        # acending
        orig = [6,5,4,3,2,1]
        dll = DLL(orig)
        insertion_sort(dll, dll.get_head(), dll.get_tail())
        assert dll == DLL(sorted(orig))

        # scattered
        orig = [1,8,2,7,3,6,4,6]
        dll = DLL(orig)
        insertion_sort(dll, dll.get_head(), dll.get_tail())
        assert dll == DLL(sorted(orig))

        # size 2
        orig = []
        dll = DLL(orig)
        insertion_sort(dll, dll.get_head(), dll.get_tail())
        assert dll == DLL([])
Beispiel #13
0
def test(n):
    print "Tempi ordinamento vettore di", n, "elementi random :"

    #CASO MEDIO (ARRAY RANDOM)

    list1 = random_list(n)
    list2 = copy_list(list1)

    #print "Vettore random da ordinare : ",list1

    start = timer()
    insertion_sort(list1)
    end = timer()
    print " - Tempo impiegato da InsertionSort :", (end - start), " secondi"

    start = timer()
    Merge_Sort(list2, 0, n - 1)
    end = timer()
    print " - Tempo impiegato da MergeSort     :", (end - start), " secondi"

    #CASO MIGLIORE (ARRAY ORDINATO)
    print "Tempi ordinamento vettore ordinato :"

    start = timer()
    insertion_sort(list1)
    end = timer()
    print " - InsertionSort :", (end - start), " secondi"

    start = timer()
    Merge_Sort(list2, 0, n - 1)
    end = timer()
    print " - MergeSort     :", (end - start), " secondi"

    #CASO PEGGIORE (ARRAY ORDINATO AL CONTRARIO)
    print "Tempi ordinamento vettore ordinato al contrario :"

    list1.reverse()
    list4 = copy_list(list1)

    start = timer()
    insertion_sort(list1)
    end = timer()
    print " - InsertionSort :", (end - start), " secondi"

    start = timer()
    Merge_Sort(list4, 0, n - 1)
    end = timer()
    print " - MergeSort     :", (end - start), " secondi"
def insertion_sort_time():

    #Create empty dictionary
    execution_time = {}

    for i in range(500, 10001, 500):

        try:
            unsorted_array = sorted(random.sample(range(i), i))
        except ValueError:
            print("Sample larger than population or is negative")

        start_time = time.time()
        sorted_array = insertion_sort(unsorted_array)
        end_time = time.time()

        #Input size and its corresponding execution time is added to dictionary
        execution_time[i] = end_time - start_time

    print(execution_time)
    plot_sorting_algorithm(execution_time)
Beispiel #15
0
 def test_insertion_sort_str(self):
     self.assertEqual(
         insertion_sort(self.str_list.get_items()),
         ["a", "a", "b", "c", "e", "g", "p", "q", "v", "z"],
     )
Beispiel #16
0
 def test_insertion_sort_int(self):
     self.assertEqual(
         insertion_sort(self.int_list.get_items()),
         [0, 0, 2, 3, 8, 9, 15, 60, 212, 300],
     )
Beispiel #17
0
import random
from bubblesort import bubble_sort
from SelectionSort import selection_sort
from InsertionSort import insertion_sort

elements = random.sample(range(10000),6000)
elements_1 = elements[:]
elements_2 = elements[:]
bubble_sort(elements) #Random Elements List
selection_sort(elements_1)
insertion_sort(elements_2)
Beispiel #18
0
from SelectionSort import selection_sort
from InsertionSort import insertion_sort
import matplotlib.pyplot as plt
import sys

sizes = [5, 10, 20, 35, 55, 80, 105, 135, 170, 210]
times = []
if sys.argv[1] == 'i':
    for i in range(0, len(sizes)):
        times.append(insertion_sort(sizes[i]))
else:
    for i in range(0, len(sizes)):
        times.append(selection_sort(sizes[i]))

for i in range(0, len(sizes)):
    plt.scatter(sizes[i], times[i])
plt.show()
        print("[3] - Merge Sort")
        print("[4] - Quick Sort")
        print("[5] - Heap Sort")
        print("[6] - KruskalMST")
        print("[7] - PrimMST")
        print("[8] - DijkstraMST")
        print("[9] - 0/1 Greedy Knapsack Problem")
        print("[10]- Exit")
        option = input("Option: ")

        if option == '1':  # Insertion Sort
            numbers, filename = process_inputfile()

            print("\nInsertion Sort running...")
            start_time = time.time()  # get initial time
            numbers = insertion_sort(numbers)
            print(
                "\n> Insertion Sort finished with sorting time: %s seconds." %
                "{0:.3f}".format(time.time() - start_time))

            generate_outputfile(numbers, "insertion_sort",
                                filename.split("in")[0])
            print(
                "---------------------------------------------------------------"
            )

            time.sleep(2)

        elif option == '2':  # Selection Sort
            numbers, filename = process_inputfile()