Exemple #1
0
def start_algorithm():
	global data, result, numbers
	
	if not data:
		return

	if (algmenu.get() == 'Selection Sort'):
		selection_sort(data, drawData)
		drawData(data, ['Green' for x in range(len(data))])
		result = "Selection Sort \n" + ' '.join(map(str, data))
		data = copy.deepcopy(numbers)

	if (algmenu.get() == 'Insertion Sort'):
		insertion_sort(data, drawData)
		drawData(data, ['Green' for x in range(len(data))])
		result = "Insertion Sort \n" + ' '.join(map(str, data))
		data = copy.deepcopy(numbers)

	if (algmenu.get() == 'Bubble Sort'):
		bubble_sort(data, drawData)
		drawData(data, ['Green' for x in range(len(data))])
		result = "Bubble Sort \n" + ' '.join(map(str, data))
		data = copy.deepcopy(numbers)

	if (algmenu.get() == 'Quick Sort'):
		quick_sort(data, 0, len(data)-1, drawData)
		drawData(data, ['Green' for x in range(len(data))])
		result = "Quick Sort \n" + ' '.join(map(str, data))
		data = copy.deepcopy(numbers)

	if (algmenu.get() == 'Merge Sort'):
		merge_sort(data, 0, len(data)-1, drawData)
		drawData(data, ['Green' for x in range(len(data))])
		result = "Merge Sort \n"' '.join(map(str, data))
		data = copy.deepcopy(numbers)
Exemple #2
0
 def select_sort():
     global array
     if var.get() == "Selection Sort":
         selection_sort(array, draw_array)
     elif var.get() == "Insertion Sort":
         insertion_sort(array, draw_array)
     elif var.get() == "Quicksort":
         quick_sort(array, 0, len(array) - 1, draw_array)
Exemple #3
0
def bucket_sort(seq, n):
    step = 1 / n
    s = []
    for i in range(n):
        t = [j for j in seq if (j >= step * i) and (j <= step * (i + 1))]
        insertion_sort(t)
        s.extend(t)
    return s
Exemple #4
0
 def test_insertion_sort(self):
     """
     Tests the insertion_sort(list) method
     """
     data = [3, 1, 10, 9]
     results = insertion_sort(data)
     self.assertIsInstance(results, tuple)
     self.assertEqual(results[0], [1, 3, 9, 10])
     data = random.sample(range(0, 100), 10)
     results = insertion_sort(data)
     self.assertEqual(results[0], sorted(data))
Exemple #5
0
def simulation():    
    
    bubble_time = 0
    selection_time = 0
    insertion_time = 0
    merge_time = 0
    quick_time = 0
    tim_time = 0
    
    for i in range(EXPERIMENTS):

        # create a list with some number of values from the given range
        my_list = random.sample(range(MAX_VALUE), LIST_SIZE)    
        start = time.time()
        bubble_sort(my_list)
        bubble_time += time.time() - start
        
        my_list = random.sample(range(MAX_VALUE), LIST_SIZE)    
        start = time.time()
        selection_sort(my_list)
        selection_time += time.time() - start
        
        my_list = random.sample(range(MAX_VALUE), LIST_SIZE)    
        start = time.time()
        insertion_sort(my_list)
        insertion_time += time.time() - start
        
        my_list = random.sample(range(MAX_VALUE), LIST_SIZE)    
        start = time.time()
        merge_sort(my_list)
        merge_time += time.time() - start
        
        my_list = random.sample(range(MAX_VALUE), LIST_SIZE)    
        start = time.time()
        quick_sort(my_list)
        quick_time += time.time() - start
        
        my_list = random.sample(range(MAX_VALUE), LIST_SIZE)    
        start = time.time()
        my_list.sort()
        tim_time += time.time() - start
        
    print('Bubble sort took', bubble_time/EXPERIMENTS*1000, 'ms')    
    print('Selection sort took', selection_time/EXPERIMENTS*1000, 'ms')    
    print('Insertion sort took', insertion_time/EXPERIMENTS*1000, 'ms')      
    print('Merge sort took', merge_time/EXPERIMENTS*1000, 'ms')    
    print('Quick sort took', quick_time/EXPERIMENTS*1000, 'ms')
    print('Timsort took', tim_time/EXPERIMENTS*1000, 'ms')
Exemple #6
0
def tim_sort(the_array):
    runs, sorted_runs = [], []
    length = len(the_array)
    new_run = [the_array[0]]

    for i in range(1, length):
        if i == length - 1:  # if i is at the end of the list
            new_run.append(the_array[i])
            runs.append(new_run)
            break
        # if the i'th element of the array is less than the one before it
        if the_array[i] < the_array[i - 1]:
            if not new_run:
                runs.append([the_array[i]])
            else:
                runs.append(new_run)
                new_run = []
        new_run.append(the_array[i])

    # for every item in runs, append it using insertion sort
    for item in runs:
        sorted_runs.append(insertion_sort(item))

    # for every run in sorted_runs, merge them
    sorted_array = []
    for run in sorted_runs:
        sorted_array = merge(sorted_array, run)

    return sorted_array
Exemple #7
0
def test_merge_sort(fixtures):
    for fixture in fixtures:
        assert merge_sort(fixture[0]) == fixture[1]
        assert quick_sort(fixture[0]) == fixture[1]
        assert insertion_sort(fixture[0]) == fixture[1]
        assert bubble_sort(fixture[0]) == fixture[1]
        assert heap_sort(fixture[0]) == fixture[1]
Exemple #8
0
def initialize(params):
    if params["type"] == "merge":
        merge_sort(params["comp"], params["n"], params["array"])

    elif params["type"] == "quick":
        quick_sort(params["comp"], params["n"], params["array"], 0,
                   params["n"] - 1)

    elif params["type"] == "insert":
        insertion_sort(params["comp"], params["n"], params["array"])

    elif params["type"] == "dual":
        dual_pivot_qs(params["comp"], params["n"], params["array"], 0,
                      params["n"] - 1)

    elif params["type"] == "hybrid":
        hybrid_sort(params["comp"], params["n"], params["array"])
Exemple #9
0
def StartAlgo():
    global data
    sp = float(speed.get())

    a = algo.get()

    if a == 'Merge Sort':
        mergesort(data, 0, len(data) - 1, Getdata, sp)
    elif a == 'Quick Sort':
        quciksort(data, 0, len(data) - 1, Getdata, sp)
    elif a == 'Bubble Sort':
        bubbleSort(data, Getdata, sp)
    elif a == 'Selection Sort':
        selection(data, Getdata, sp)
    elif a == 'Insertion Sort':
        insertion_sort(data, Getdata, sp)

    Getdata(data, ['blue' for i in range(len(data))])
Exemple #10
0
def bucketsort(vector, bucketSize=DEFAULT_BUCKET_SIZE):

    # se o tamanho do vetor for igual a = 0 ele ja esta ordenado
    if len(vector) == 0:
        return vector

    # Determinar o minimo e o valor máximo
    minValue = vector[0]
    maxValue = vector[0]

    for i in range(1, len(vector)):
        if vector[i] < minValue:
            minValue = vector[i]
        elif vector[i] > maxValue:
            maxValue = vector[i]

    bucketCount = math.floor((maxValue - minValue) / bucketSize) + 1
    # 81 - 6 = 75/5 = 15 + 1 = [16]

    #initialize buckets
    buckets = []
    for i in range(0, bucketCount):
        buckets.append([])

    #put the values in bucketsort

    for i in range(0, len(vector)):
        buckets[math.floor(
            (vector[i] - minValue) / bucketSize)].append(vector[i])
        #append the value 22 on buckets[3]
        # append the value 45 on bucket[7]
        #append the value 12 on bucket [1]

    #sorted buckets and place back

    new_vector = []
    for i in range(0, len(buckets)):
        insertion_sort(buckets[i])
        for j in range(0, len(buckets[i])):
            new_vector.append(buckets[i][j])

    yield new_vector
def shell_sort(a, inc):
    i, j = 0, 0

    while j < inc:
        # get numbers
        ToSort = []
        while i * inc + j < len(a):
            ToSort.append(a[i * inc + j])
            i += 1
        # i = 0

        # sort numbers
        insertion_sort(ToSort)

        # return numbers
        for i, num in list(enumerate(ToSort)):
            a[i * inc + j] = num
        i = 0
        j += 1

    return insertion_sort(a)
Exemple #12
0
def quick_sort(array):
    # If the array has one or zero elements, it is already sorted
    if len(array) <= 1:
        return array
    elif len(array) < 5:
        # Uses insertion sort on short arrays, for efficiency
        return insertion_sort(array)

    partition = array[randint(0, len(array) - 1)]
    left = []
    right = []
    for num in array:
        if num < partition:
            left.append(num)
        else:
            right.append(num)
    left = quick_sort(left)
    right = quick_sort(right)
    return left + right
def test_binary(binary):
    insertion_sort(binary)
    assert binary == [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
Exemple #14
0
def test_random_lists_always_sorted(to_sort, pre_sorted):
    """Test insertion sort works for 100 random lists."""
    assert insertion_sort(to_sort) == pre_sorted
def test_random_list():
    lst = insertion_sort([4, 3, 8, 5, 0, 2, 56, 9, 68, -1])
    assert lst == [-1, 0, 2, 3, 4, 5, 8, 9, 56, 68]
def test_alphabet():
    lst = insertion_sort(['a', 'b', 'f', 'e', 'y', 'w', 'i', 'c', 'p'])
    assert lst == ['a', 'b', 'c', 'e', 'f', 'i', 'p', 'w', 'y']
def test_big(big):
    insertion_sort(big)
    assert big == range(10000)
Exemple #18
0
def test_insertion():
    A = [i for i in range(100, 0, -1)]
    insertion_sort(A)
    assert A == B
Exemple #19
0
    def __init__(self, name, listing):
        # Initilization steps
        self.name = name
        listing_copy = listing
        listing_copy2 = listing
        self.listing = listing_copy

        ##################################################
        # For each algorithm, the accuracy, time, and list
        # will be tracked using the methods shown below
        ##################################################

        # Python sort will be used as the master sort
        listing_copy_py = listing_copy
        start = timer()
        self.python_sorted_list = python_sort(listing_copy_py)
        end = timer()
        self.python_sorted_time = end - start
        # Bubble Sort will be tested against python sort
        listing_copy_bu = listing_copy
        start = timer()
        self.bubble_sorted_list = bubble_sort(listing_copy_bu)
        end = timer()
        self.bubble_sort_accurate = False
        if self.bubble_sorted_list == self.python_sorted_list:
            self.bubble_sort_accurate = True
        self.bubble_sort_time = end - start
        # Selection sort will be tested against python sort
        listing_copy_sel = listing_copy
        start = timer()
        self.selection_sorted_list = selection_sort(listing_copy_sel)
        end = timer()
        self.selection_sort_accurate = False
        if self.selection_sorted_list == self.python_sorted_list:
            self.selection_sort_accurate = True
        self.selection_sort_time = end - start
        # Merge sort will be tested against python sort
        listing_copy_mer = listing_copy
        start = timer()
        self.merge_sorted_list = merge_sort(listing_copy_mer)
        end = timer()
        self.merge_sort_accurate = False
        if self.merge_sorted_list == self.python_sorted_list:
            self.merge_sort_accurate == True
        self.merge_sort_time = end - start
        #Shell root sort will be tested against python sort
        listing_copy_she = listing_copy
        start = timer()
        self.shell_sorted_list = shell_sort(listing_copy_she)
        end = timer()
        self.shell_accurate = False
        if self.shell_sorted_list == self.python_sorted_list:
            self.shell_accurate = True
        self.shell_time = end - start
        #Insertion sort will be tested against python sort
        listing_copy_ins = listing_copy
        start = timer()
        self.insertion_sorted_list = insertion_sort(listing_copy_ins)
        end = timer()
        self.insertion_accurate = False
        if self.insertion_sorted_list == self.python_sorted_list:
            self.insertion_accurate = True
        self.insertion_time = end - start

        # Heap sort will be tested against python sort
        listing_copy_hea = listing_copy
        start = timer()
        self.heap_sorted_list = heap_sort(listing_copy_hea)
        end = timer()
        self.heap_accurate = False
        if self.heap_sorted_list == self.python_sorted_list:
            self.heap_accurate = True
        self.heap_time = end - start

        #Strand sort will be tested against python sort
        listing_copy_strand = listing_copy2

        start = timer()

        self.strand_sorted_list = strand_sort(listing_copy_strand)
        end = timer()
        self.strand_accurate = False
        if self.strand_sorted_list == self.python_sorted_list:
            self.strand_root_accurate = True
        self.strand_time = end - start
def test_bubble():
    """test insertion sort function on list of ints."""
    a = [123, 55, 2, 7, 22, -10, 1]
    insertion_sort(a)
    assert a == [-10, 1, 2, 7, 22, 55, 123]
def test_bubble_letters_input():
    """test insertion sort function on list of strings."""
    a = ["a", "b"]
    insertion_sort(a)
    assert a == ["a", "b"]
def test_bubble_empty_input():
    """test insertion sort function on empty list."""
    a = []
    insertion_sort(a)
    assert a == []
Exemple #23
0
def test_insertion_non_list_raises_error():
    """Entering a non-list/tuple param raises an error."""
    from insertion import insertion_sort
    with pytest.raises(TypeError):
        insertion_sort('Hello')
# coding=utf-8
# Python3

#
# DESCRIPCION: Aplicación del algoritmo de ordenamiento asertionsort.
#

# Autores:
#	Gregory Muñoz, Ka Shing Fung Ng
#
# Ultima modificacion: 20/09/2019
#

from insertion import insertion_sort

with open('dato.txt', 'r') as f:
    A = f.readlines()
    f.closed

array_size = len(A)

insertion_sort(A, array_size)
Exemple #25
0
def test_insertion_sort_sorts_random_list():
    """Insertion sort returns an ordered list."""
    from insertion import insertion_sort
    input = [randint(0, 1000) for i in range(100)]
    expected = sorted(input)
    assert insertion_sort(input) == expected
Exemple #26
0
def test_insertion_sort_returns_ordered_list(input, expected):
    """Insertion sort returns an ordered list."""
    from insertion import insertion_sort
    assert insertion_sort(input) == expected
def test_immutable():
    with pytest.raises(TypeError):
        insertion_sort("nope")
Exemple #28
0
def test_insertion_sort_list_duplicates():
    """Can sort list utilizing insertion sort method"""
    nums = [23, 1, 5, -69, 808, 808, -420, 33, 33, 1986]
    actual = insertion_sort(nums)
    expected = [-420, -69, 1, 5, 23, 33, 33, 808, 808, 1986]
    assert actual == expected
Exemple #29
0
def test_insertion_sort(array: List[int]):
    """Checks that returned array is the same as result of sorted()"""
    assert sorted(array) == insertion_sort(array)
Exemple #30
0
def test_insertion_sort_list_string():
    """Can sort list utilizing insertion sort method"""
    nums = [23, 1, '5', -69, 808, -420, '33', 1986]
    actual = insertion_sort(nums)
    expected = [-420, -69, 1, 5, 23, 33, 808, 1986]
    assert actual == expected
Exemple #31
0
def excec_program(list, args, file):
    list_dup = list.copy()
    swaps = 0
    compares = 0
    my_time = 0

    if args[0] == "insert":
        if file:
            t1_start = time.process_time()
            insertion.insertion_sort_stat(list, args[1])
            t1_stop = time.process_time()
        else:
            t1_start = time.process_time()
            insertion.insertion_sort(list, args[1])
            t1_stop = time.process_time()
        swaps = insertion.swaps
        compares = insertion.compares
        my_time = round(t1_stop - t1_start, 8)


    elif args[0] == "merge":
        merge.reset_counters()
        if file:
            t1_start = time.process_time()
            merge.merge_sort_stat(list, args[1])
            t1_stop = time.process_time()
        else:
            t1_start = time.process_time()
            merge.merge_sort(list, args[1])
            t1_stop = time.process_time()
        swaps = merge.swaps
        compares = merge.compares
        my_time = round(t1_stop - t1_start, 8)


    elif args[0] == "quick":
        quick.reset_counters()
        if file:
            t1_start = time.process_time()
            quick.quick_sort_stat(list, 0, len(list) - 1, args[1])
            t1_stop = time.process_time()
        else:
            t1_start = time.process_time()
            quick.quick_sort(list, 0, len(list) - 1, args[1])
            t1_stop = time.process_time()
        swaps = quick.swaps
        compares = quick.compares
        my_time = round(t1_stop - t1_start, 8)

    elif args[0] == "dual_pivot":
        dual_pivot.reset_counters()
        if file:
            t1_start = time.process_time()
            dual_pivot.dual_sort_stat(list, 0, len(list) - 1, args[1])
            t1_stop = time.process_time()
            # print(list)
        else:
            t1_start = time.process_time()
            dual_pivot.dual_sort(list, 0, len(list) - 1, args[1])
            t1_stop = time.process_time()
        swaps = dual_pivot.swaps
        compares = dual_pivot.compares
        my_time = round(t1_stop - t1_start, 8)

    elif args[0] == "hybrid":
        hybrid.reset_counters()
        if file:
            t1_start = time.process_time()
            hybrid.hybrid_sort(list, args[1])
            t1_stop = time.process_time()
        else:
            t1_start = time.process_time()
            hybrid.hybrid_sort(list, args[1])
            t1_stop = time.process_time()
        swaps = hybrid.swaps
        compares = hybrid.compares
        my_time = round(t1_stop - t1_start, 8)

    if file:
        info = str(len(list)) + ';'
        info += str(swaps) + ';'
        info += str(compares) + ';'
        info += str(my_time) + ';'
        info += ('\n')
        try:
            file_name = args[2]
            with open(file_name,'a+') as f:
                f.write(info)
        except FileNotFoundError:
            print("Creating new file ...")
            with open(file_name,'a+') as f:
                f.write(info)
    else:
        print("-----------------")
        print("Time: %.10f" % (t1_stop - t1_start))
        print("Swaps: ", swaps)
        print("Compares: ", compares)
        sorted_info(list_dup, list)
        if check_order:
            print(list)
        else:
            print("Something went wrong :( )")
Exemple #32
0
#!/usr/bin/env python3

import sort_utils
from insertion import insertion_sort

tests_passed = 0
total_tests = 0

test_name = "Test 1 - a"
print(f"---- {test_name} ----------------------------")
orig = li = [12, 7, 32, 5, 16, 4]
li = list(orig)
insertion_sort(li)
print(li)
print("\n".join([
    "---- Expected output -------------------------",
    "[12, 7, 32, 5, 16, 4]",
    "swap 0:12 <--> 1:7",
    "[7, 12, 32, 5, 16, 4]",
    "swap 2:32 <--> 3:5",
    "[7, 12, 5, 32, 16, 4]",
    "swap 1:12 <--> 2:5",
    "[7, 5, 12, 32, 16, 4]",
    "swap 0:7 <--> 1:5",
    "[5, 7, 12, 32, 16, 4]",
    "swap 3:32 <--> 4:16",
    "[5, 7, 12, 16, 32, 4]",
    "swap 4:32 <--> 5:4",
    "[5, 7, 12, 16, 4, 32]",
    "swap 3:16 <--> 4:4",
    "[5, 7, 12, 4, 16, 32]",
def test_empty(empty):
    insertion_sort(empty)
    assert empty == []
def test_unsorted(unsorted):
    insertion_sort(unsorted)
    assert unsorted == [-3, 1, 2, 3, 4, 5, 5.5, 6, 7, 8, 9, 10]
def test_empty_string():
    lst = insertion_sort([2, 5, 'a', 7, 'd', 0, '', 'o'])
    assert lst == [0, 2, 5, 7, '', 'a', 'd', 'o']
Exemple #36
0
 def _test_true_false(self, ulist, expectation):
     slist = insertion.insertion_sort(ulist)
     self.assertEqual(slist, expectation)
def test_empty_list():
    lst = insertion_sort([])
    assert lst == []
Exemple #38
0
 def _test_eq(self, ulist):
     slist = insertion.insertion_sort(ulist)
     expected = sorted(ulist)
     self.assertEqual(slist, expected)
def test_one(one):
    insertion_sort(one)
    assert one == [5]
Exemple #40
0
DEFAULT_BUCKET_SIZE = 5

if __name__ == "__main__":
    number_interation = int(input("Digite o numero de inteiros: "))

    input_message = "Selecione o metodo que deseja executar\n(i)nsertion sort\n(b)ucket sort\n(m)erge sort\n(s)hell sort\n(q)uick sort\n(r)adix sort\n(h)heap sort"
    input_is = input(input_message)

    # Build and randomly shuffle list of integers.
    vector = [x + 1 for x in range(number_interation)]
    random.seed(time.time())
    random.shuffle(vector)

    if input_is == "i":
        title = "Insertion Sort"
        generator = insertion_sort(vector)
    elif input_is == "b":
        title = "Bucket Sort"
        generator = bucketsort(vector, bucketSize=DEFAULT_BUCKET_SIZE)
    elif input_is == "m":
        title = "Merge Sort"
        generator = mergesort(vector, 0, number_interation - 1)
    elif input_is == "s":
        title = "Shell Sort"
        generator = shellsort(vector)
    elif input_is == "q":
        title = "Quick Sort"
        generator = quicksort_graph(vector, 0, number_interation - 1)
    elif input_is == "h":
        generator = heapsort(vector)
        title = 'heapsort'
Exemple #41
0
def test_insertion_sort_list_unique():
    """Can sort list utilizing insertion sort method"""
    nums = [23, 1, 5, 69, 808, 420, 33, 1986]
    actual = insertion_sort(nums)
    expected = [1, 5, 23, 33, 69, 420, 808, 1986]
    assert actual == expected
Exemple #42
0
def test_insertion_non_int_raises_error():
    """Entering an iterable containing non-integers raises an error."""
    from insertion import insertion_sort
    with pytest.raises(ValueError):
        insertion_sort([1, 2, 3, 5, 'burp'])
from insertion import rec_ins_sort, insertion_sort
seq = [1, 5, 3, 2]
insertion_sort(seq)
print(seq)
def insertion(*args):
	return insertion_sort(*args)