Exemple #1
0
def time_merge_sort(input_sizes):
    print("\nMerge Sort: Beginning timing...")

    # init array to store results and return later
    time_arr = []

    # repeat for each input size
    for size in input_sizes:
        # setup the test array
        test_arr = random.sample(range(0, size), size)

        # calculate left index and right index
        left_index = 0
        right_index = size - 1

        # print input size
        print(f"Merge Sort: input size: {size}", end=', ')

        # log the start time
        time_start = time.time()

        # call merge sort
        mergesort(test_arr, left_index, right_index)

        # log the stop time and find the time delta
        time_stop = time.time()
        delta = time_stop - time_start

        # print results and add to time results array
        print(f"time: {delta} seconds")
        time_arr.append(delta)

    # return results
    return time_arr
Exemple #2
0
    def test_merges_larger_edge_set(self):
        larger_inputs = [
            [0, 1, 1],
            [1, 2, 4],
            [2, 3, 6],
            [3, 1, 5],
            [4, 3, 4],
            [5, 6, 2],
            [6, 7, 2],
            [7, 9, 1],
            [8, 2, 2],
            [9, 0, 5],
            [10, 7, 2],
            [11, 3, 4],
            [12, 4, 8],
            [13, 6, 2],
            [14, 1, 3],
            [15, 4, 9],
        ]

        vertices = [Vertex(id, x, y) for id, x, y in larger_inputs]
        edge_list = create_edge_list(vertices)
        mergesort(edge_list, comparator=distance_comparator)

        prev_distance = 0
        for edge in edge_list:
            dist = edge.distance - prev_distance
            if dist < 0:
                raise Exception('Merge did not sort by distance asc')
Exemple #3
0
 def test_merges_empty_array(self):
     arr = []
     mergesort(arr)
     self.assertSequenceEqual(
         arr,
         [],
     )
def timsort(val_list, k):
    if len(val_list) <= k:
        insertion_sort(val_list)
    elif len(val_list) > 1:
        mid_index = len(val_list) // 2
        left = val_list[:mid_index]
        right = val_list[mid_index:]
        
        mergesort(left)
        mergesort(right)
        
        val_index = 0
        l_index = 0
        r_index = 0
        
        while r_index < len(right) and l_index < len(left):
            if right[r_index] < left[l_index]:
                val_list[val_index] = right[r_index]
                r_index += 1
            else:
                val_list[val_index] = left[l_index]
                l_index += 1
            val_index += 1
            
        while r_index < len(right):
            val_list[val_index] = right[r_index]
            r_index += 1
            val_index += 1
            
        while l_index < len(left):
            val_list[val_index] = left[l_index]
            l_index += 1
            val_index += 1
    return(val_list)
Exemple #5
0
    def test_merges_already_sorted_array(self):
        arr = [-3, -2, -1, 0, 1, 2, 3]
        mergesort(arr)

        self.assertSequenceEqual(
            arr,
            [-3, -2, -1, 0, 1, 2, 3],
        )
Exemple #6
0
    def test_merges_multiple_same_entries(self):
        arr = [1, 1, 3, -2, -2, -5, 5, 3, -2]
        mergesort(arr)

        self.assertSequenceEqual(
            arr,
            [-5, -2, -2, -2, 1, 1, 3, 3, 5],
        )
Exemple #7
0
def test_merge(l):
	result = 0
	for x in range(10):
		arr = copy(l)
		t = time.time()
		mergesort(l)
		result += time.time() - t
	return result
Exemple #8
0
    def test_merges_reversed_array(self):
        arr = [3, 2, 1, 0, -1, -2, -3]
        mergesort(arr)

        self.assertSequenceEqual(
            arr,
            [-3, -2, -1, 0, 1, 2, 3],
        )
Exemple #9
0
def containssum(n, a):
	mergesort(a)
	for i in range(len(a)):
		print("Executed {0} times").format(i)
		v = n - a[i]
		found = binarysearch(a, v)
		if found != None and found != i:
			return True
	return False
    def testSort(self):
        a = [1,2,3,4,5,6,7,8,9]
        self.assertEqual(mergesort.mergesort(a), [1,2,3,4,5,6,7,8,9])

        b = [8,7,6,5,4,3,2,1]
        self.assertEqual(mergesort.mergesort(b), [1,2,3,4,5,6,7,8])

        c = [1,6,3,2,1,9,7,5,4,9]
        self.assertEqual(mergesort.mergesort(c), [1,1,2,3,4,5,6,7,9,9])
    def testSort(self):
        a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        self.assertEqual(mergesort.mergesort(a), [1, 2, 3, 4, 5, 6, 7, 8, 9])

        b = [8, 7, 6, 5, 4, 3, 2, 1]
        self.assertEqual(mergesort.mergesort(b), [1, 2, 3, 4, 5, 6, 7, 8])

        c = [1, 6, 3, 2, 1, 9, 7, 5, 4, 9]
        self.assertEqual(mergesort.mergesort(c),
                         [1, 1, 2, 3, 4, 5, 6, 7, 9, 9])
Exemple #12
0
 def test_mergesort(self):
     self.assertEqual(mergesort([]), [])
     self.assertEqual(mergesort([1]), [1])
     self.assertEqual(mergesort([1,1]), [1,1])
     self.assertEqual(mergesort([1,2]), [1,2])
     self.assertEqual(mergesort([2,1]), [1,2])
     self.assertEqual(mergesort([2,-1]), [-1,2])
     self.assertEqual(mergesort([3,1,2]), [1,2,3])
     self.assertEqual(mergesort([1,2,3,4]), [1,2,3,4])
     self.assertEqual(mergesort([2,1,3,4]), [1,2,3,4])
     self.assertEqual(mergesort([3,4,1,2]), [1,2,3,4])
Exemple #13
0
 def test_mergesort(self):
     self.assertEqual(mergesort([]), [])
     self.assertEqual(mergesort([1]), [1])
     self.assertEqual(mergesort([1, 1]), [1, 1])
     self.assertEqual(mergesort([1, 2]), [1, 2])
     self.assertEqual(mergesort([2, 1]), [1, 2])
     self.assertEqual(mergesort([2, -1]), [-1, 2])
     self.assertEqual(mergesort([3, 1, 2]), [1, 2, 3])
     self.assertEqual(mergesort([1, 2, 3, 4]), [1, 2, 3, 4])
     self.assertEqual(mergesort([2, 1, 3, 4]), [1, 2, 3, 4])
     self.assertEqual(mergesort([3, 4, 1, 2]), [1, 2, 3, 4])
def startalgorithm():
    global data
    if n.get() == "Bubble Sort":
        bubblesort(data, speedy.get(), drawdata)
    if n.get() == "Selection Sort":
        selectionsort(data, speedy.get(), drawdata)
    if n.get() == "Insertion Sort":
        insertionsort(data, speedy.get(), drawdata)
    if n.get() == "Merge Sort":
        mergesort(data, speedy.get(), drawdata)
    if n.get() == "Quick Sort":
        quick_sort(data, drawdata, speedy.get())
def test_mergesort():
    test_list = [randint(1, 50) for i in range(15)]
    test_sorted = test_list[:]
    mergesort(test_sorted, 0, 14)
    if test_sorted == sorted(test_list):
        print("test passes")
        print(test_list)
        print(test_sorted)
    else:
        print("test fails")
        print(test_list)
        print(test_sorted)
Exemple #16
0
 def test_merges_only_between_given_indices(self):
     """
     Not actually sure we need this, saw that we had functionality
     for it so I'd rather test for it and remove later if we don't need it
     rather than break it and find out we do need it.
     """
     arr = [3, 2, 6, 1, 4, 4, 7, 2, 3, 4]
     mergesort(arr, 1, 4)
     self.assertSequenceEqual(
         arr,
         [3, 1, 2, 4, 6, 4, 7, 2, 3, 4],
     )
Exemple #17
0
    def test_mergesort(self):
        arr = []
        arr = mergesort(arr)
        self.assertEqual(arr, [])

        arr = [i for i in range(9, -1, -1)]
        arr = mergesort(arr)
        self.assertEqual(arr, [i for i in range(10)])

        arr = [5, 6, 1, 3, 8, 2, 1]
        arr = mergesort(arr)
        self.assertEqual(arr, [1, 1, 2, 3, 5, 6, 8])
Exemple #18
0
    def test_basic_edge_list(self):
        coords = [[1, 1], [2, 4], [3, 6], [1, 5], [3, 4], [6, 2]]
        cities = [
            Vertex(i, coord[0], coord[1]) for i, coord in enumerate(coords)
        ]

        edge_list = create_edge_list(cities)
        mergesort(edge_list, comparator=distance_comparator)

        tour_list, distance = create_tour(edge_list, len(cities))

        self.assertEqual(len(tour_list), 6)
        self.assertEqual(distance, 18)
        edge_vertices = [[edge.v1.id, edge.v2.id] for edge in tour_list]
        self.assertSequenceEqual(
            edge_vertices,
            [[1, 3], [1, 4], [2, 3], [0, 4], [0, 5], [2, 5]],
        )
Exemple #19
0
    def test_merges_with_comparator_function(self):
        arr = [
            {
                'val': 4
            },
            {
                'val': 1
            },
            {
                'val': 3
            },
            {
                'val': 2
            },
            {
                'val': 0
            },
        ]

        def _comparator(x, y):
            return x['val'] <= y['val']

        mergesort(arr, comparator=_comparator)

        self.assertSequenceEqual(
            arr,
            [
                {
                    'val': 0
                },
                {
                    'val': 1
                },
                {
                    'val': 2
                },
                {
                    'val': 3
                },
                {
                    'val': 4
                },
            ],
        )
Exemple #20
0
def dSelect(array, orderStatistic):
	# select the i-th smallest or largest element in an unsorted array.
	if len(array) == 1:
		return array[0]
	else:
		# split array in to arrays of length 5.
		n = len(array)
		fifths = []
		medians = []
		for i in range(0, n, 5):
			fifths.append(array[i:i+5])
		# choose pivot as median of medians.
		for x in fifths:
			mergesort(x)
		 	medians.append(x[len(x)/2])		
		pivot = dSelect(medians, len(medians)/2)
		pivotIndex = array.index(pivot)		
		
		# move pivot to front of array.
		
		array[0], array[pivotIndex] = array[pivotIndex], array[0]
		# print 'start', array
		# iterate through array[1:]
		# if x is smaller than pivot, move it to the front
		# of the list by swapping its position with the smallest
		# x larger than pivot.
		j = 0  		# index of first number larger than pivot
		for i in range(1, len(array)):
			if array[i] < pivot:
				array[i], array[j + 1] = array[j + 1], array[i]
				j += 1
			if array[i] > pivot:
				pass
		# move pivot to array[j]
		array[0], array[j] = array[j], array[0]
		# print "pivot", pivot, "array[0]", array[0]
		# print'ordered', array 
		# check new pivot position against orderStatistic
		if j == orderStatistic:
			return pivot
		if j > orderStatistic:
			return dSelect(array[:j], orderStatistic)
		if j < orderStatistic:
			return dSelect(array[j:], orderStatistic - j)
def test_mergesort(my_list):

    test_mergesort.counter += 1
    mergesort(my_list)
    try:
        for element in my_list:
            if (not element == float(element)):
                raise ValueError
    except ValueError:
        pass
    except:
        print(
            "CONGRATULATIONS you have found bu.. feature from my unbreakable code!\nPlease inform the author how did you do this! :)"
        )
    else:
        if (sorted(my_list) == my_list):
            print("Sorting complete!")
    finally:
        print("Test number " + str(test_mergesort.counter) + " over\n")
Exemple #22
0
def test_mergesort_on_long_list():
    """Test mergesort on long list."""
    from mergesort import mergesort
    unsorted_list = []
    for i in range(100):
        unsorted_list.append(random.randint(0, 1000))

    sorted_list = mergesort(unsorted_list)

    assert sorted_list == sorted(unsorted_list)
Exemple #23
0
def exercise_quicksort():
    '''
    Prints solution to algorithms week 2 programming problems (edit quicksort
    to use appropriate pivot selection).
    '''
    import mergesort
    f = open("quicksort_tests/QuickSort.txt", "r")
    A = [int(i) for i in f]
    A, comp = quicksort(A)
    assert mergesort.mergesort(A) == A
    print comp
 def test2_sort(self):
     """test mergesort"""
     start_time = time.time()
     self.assertEqual(mergesort.mergesort([2,1]), [1,2]);
     list99 = range(1,100);
     list99.reverse();
     self.assertEqual(mergesort.mergetest(100), range(1,100));
     self.assertEqual(mergesort.mergetest(1000), range(1,1000));
     end_time = time.time()
     print('')
     print('time for small tests', end_time - start_time, 'seconds')
def binary_search(a,s):
	a=mergesort(a)
	n=len(a)
	if n>0:
		mid=a[n/2]
		if mid ==s:
			return True
		elif s < mid:
			return binary_search(a[:n/2],s)
		elif s> mid:
			return binary_search(a[(n/2)+1:],s)
	return False
Exemple #26
0
def main():
    start_time = time.time()
    Lista = []
    Lista.extend(range(10000, -1, -1))
    #burbuja = Burbuja(Lista)
    #burbuja_rec = br(Lista)

    print("Arreglo desordenado\t", Lista)
    Lista_ordenada = mergesort.mergesort(Lista)
    #Lista_ordenada = burbuja.ordenar()
    #Lista_ordenada = burbuja_rec.ordenar(0)
    print("Arreglo ordenado\t", Lista_ordenada)
    print("--- %s seconds ---" % round(time.time() - start_time, 2))
Exemple #27
0
def test_quicksort():
    '''
    Answers are:
    size    first   last    median
    10      25      29      21
    100     615     587     518
    1000    10297   10184   8921
    '''
    import mergesort
    for n in [10, 100, 1000]:
        f = open("quicksort_tests/" + str(n) + ".txt", "r")
        A = [int(i) for i in f]
        A, comp = quicksort(A)
        assert mergesort.mergesort(A) == A
        print comp
 def agregarContacto(self, usuario):
     c = self.contactos
     if c == None:
         self.contactos = Lista(usuario, None)
         return True
     else:
         repetido = False
         count = 0
         while c != None:
             count += 1
             c = c.next
         c = self.contactos
         while c != None:
             if c.element.nombre == usuario.nombre:
                 print("El contacto ya está en la lista")
                 repetido = True
                 break
             else:
                 c = c.next
         if repetido == False:
             c = self.contactos
             self.centinela = self.contactos
             lista = ArrayT(count + 1)
             t = 0
             while c != None:
                 lista[count] = c.element
                 c = c.next
                 count -= 1
                 t += 1
             lista[0] = usuario
             t = t + 1
             ordenado = mergesort(lista)
             for x in range(t):
                 self.centinela.element = ordenado[x]
                 if x != t - 2:
                     self.centinela = self.centinela.next
                 elif x == t - 2:
                     self.centinela.next = Lista(ordenado[x + 1], None)
                     self.centinela = self.centinela.next
                 else:
                     pass
             return True
         else:
             return False
def knapsack(csvlist, bagweight):

    profitweightratio = []
    bag = []
    # ratio of p/w (profit/weight)
    for x in csvlist:

        ratio = x['profit'] / x['weight']
        profitweightratio.append({
            "key": x['key'],
            "ratio": ratio,
            "weight": x['weight']
        })

    #once you have the ratio
    # next is sort the data
    sorted_profitweightratio = mergesort.mergesort(profitweightratio, 0,
                                                   len(profitweightratio) - 1)

    maxbagweight = 0.0
    i = 0

    while maxbagweight <= float(bagweight):

        try:
            # need to check those data should i add in the bag or not
            future_maxbagweight = maxbagweight + sorted_profitweightratio[i][
                'weight']

            if future_maxbagweight < float(bagweight):

                bag.append(sorted_profitweightratio[i])
                maxbagweight = future_maxbagweight

            i = i + 1

        except IndexError:

            break

    return bag
Exemple #30
0
def merge_pl(posting_lists):
	sorted_pls = []
	for pl in posting_lists:
		pl = ms.mergesort(pl)
		sorted_pls.append(pl)
	while len(sorted_pls) > 1:
		pl1 = sorted_pls.pop(0)
		pl2 = sorted_pls.pop(0)
		pl_combined = ms.merge(pl1, pl2)
		sorted_pls.append(pl_combined)
	posting_list = []
	last_entry = [None]
	while len(sorted_pls[0]) > 0:
		new_entry = sorted_pls[0].pop(0)
		if last_entry[0] != new_entry[0]:
			if last_entry != [None]:
				posting_list.append(last_entry)
			last_entry = new_entry
		else:
			new_docs = last_entry[1]+new_entry[1]
			last_entry = [last_entry[0], new_docs]
	if last_entry != [None]:
		posting_list.append(last_entry)
	return posting_list
Exemple #31
0
import mergesort

in_list = [1, 5, 3, 4, 9, 15, 11, 3, 4, 87, 54, 34, 12, 13]
sorted_list = sorted(in_list)
out_list = mergesort.mergesort(in_list)

print(in_list)
print(out_list)
print(sorted_list)
Exemple #32
0
    def test_normal_input(self):
        array = [7, 5, 6, 8, 9, 0, 3, 4, 2, 2, 1]
        output = [0, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9]

        mergesort(array, 0, len(array) - 1)
        self.assertEqual(array, output)
Exemple #33
0
from median_3 import quicksort_3
from median_5 import quicksort_5

import time
import csv
import random
import sys
import copy

sys.setrecursionlimit(20000)
results = [1, 2, 3, 4, 5, 6, 1, 3, 4, 1, 10]
for i in range(10, 21):
    lst = [random.randint(1, 70) for j in range(2**i)]

    start = time.time()
    merge_count = mergesort(copy.deepcopy(lst))[1]
    end = time.time()
    merge_time = end - start
    #
    # start = time.time()
    # quick_count = quicksort(copy.deepcopy(lst), 0, (2 ** i) - 1, results[i%10])[1]
    # end = time.time()
    # quick_time = end - start

    start = time.time()
    rand_count = randomized_quicksort(copy.deepcopy(lst), 0, (2**i) - 1)[1]
    end = time.time()
    rand_time = end - start

    start = time.time()
    med3_count = quicksort_3(copy.deepcopy(lst), 0, (2**i) - 1)[1]
def testmerge(a,i,k):
    started = time_ns()
    mergesort(a,0,len(a)-1)
    ended = (time_ns() - started)
    outputfile(i,k,'merge',ended)
 def test_mergesort_with_not_distinct_list(self):
   sortedresult = mergesort(self.unsortedNotDistinct)
   self.assertEqual(sortedresult, [1,1,2,2,3,3])
Exemple #36
0
from mergesort import mergesort

arr = [3, 7, 8, 5, 2, 1, 9, 5, 4]
mergesort(arr)
assert sorted(arr) == arr
Exemple #37
0
    print('Quicksort (Lomuto)')
    n = [random.randint(0, 99) for _ in range(20)]
    print(n)
    snl = quicksort_lomuto(n)
    print(snl)
    assert(snl == sorted(n))
    print()

    print('Quicksort (Hoare)')
    n = [random.randint(0, 99) for _ in range(20)]
    print(n)
    snh = quicksort_hoare(n)
    print(snh)
    assert(snh == sorted(n))
    print()

    print('Heapsort')
    n = [random.randint(0, 99) for _ in range(20)]
    print(n)
    snheap = heapsort.heapsort(n)
    print(snheap)
    assert(snheap == sorted(n))
    print()

    print('Mergesort')
    n = [random.randint(0, 99) for _ in range(20)]
    print(n)
    snm = mergesort.mergesort(n)
    print(snm)
    assert(snm == sorted(n))
Exemple #38
0
"""
ASTR 598 HW 6
Brett Morris
"""
from __future__ import print_function # Python 2 compatibility
import numpy as np
import time
import matplotlib.pyplot as plt

from mergesort import mergesort

sizes = [1e2, 1e4, 1e6, 1e8]
runtimes = []
n_trials = 2
for size in sizes:
    int_list = np.random.randint(0, 1000, size)
    runtime = []
    for trial in range(n_trials):
        start = time.time()
        mergesort(int_list)
        end = time.time()
        runtime.append(end-start)
    print(runtime)
    runtimes.append(np.mean(runtime))

plt.loglog(sizes, runtimes)
plt.xlabel('Array length')
plt.ylabel('Runtime [s]')
plt.savefig('runtime.png', bbox_inches='tight')
plt.close()
Exemple #39
0
#!/usr/bin/env python

import sys
import random
from timeit import timeit

from bubblesort    import bubblesort
from mergesort     import mergesort
from quicksort     import quicksort
from insertionsort import insertionsort
from gnomesort     import gnomesort
from selectionsort import selectionsort
from heapsort      import *

#elements = sys.argv[1:]
## we need ints, not strings
#elements = list(map(int, elements))

elements = [ random.randint(1,20) for _ in range(20) ]

print(elements)
print(bubblesort(elements[:]))
print(mergesort(elements[:]))
print(quicksort(elements[:]))
print(insertionsort(elements[:]))
print(gnomesort(elements[:]))
print(selectionsort(elements[:]))
print(heapsort(elements[:]))
Exemple #40
0
'''
	T(n) = 2T(n/2)+O(n)
	T(n) = O(nlogn)
'''

import time;

from mergesort import mergesort;

file = open("time.txt", "w");

max = 90;
n = range(1, max);

for i in n:
	array = [];
	for j in range(1, i+1):
		array.append(i-j+1);

	start = time.time();
	mergesort(array);
	end = time.time();

	file.write(str(i) + " " + str(end-start) + "\n");
Exemple #41
0
def test_str_sort():
    from mergesort import mergesort
    items = ["BB", "A", "C", "DAAX", "BA"]
    sorted_items = ["A", "BA", "BB", "C", "DAAX"]
    assert mergesort(items) == sorted_items
 def test2(self):
     stimulus = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3]
     response = [1, 1, 2, 3, 3, 3, 4, 5, 5, 5, 6, 7, 8, 9, 9, 9]
     self.assertEqual(response, mergesort(stimulus))
Exemple #43
0
"""
ASTR 598 HW 6
Brett Morris
"""
from __future__ import print_function # Python 2 compatibility

from mergesort import mergesort

# Twenty randomly shuffled integers from 1 to 21
integers = [16, 13, 10, 12, 15, 6, 11, 3, 19, 1, 20, 9, 7,
            2, 5, 4, 14, 18, 17, 8]

sorted_integers = mergesort(integers)

print(sorted_integers)
Exemple #44
0
def test_str_sort():
    items = ["BB", "A", "C", "DAAX", "BA"]
    sorted_items = ["A", "BA", "BB", "C", "DAAX"]
    assert mergesort(items) == sorted_items
    Complexity Analysis: O(nlogn) on average.
"""

from test_utilities import compare_arr_sorted_equal, summarize_results
from time import clock
from mergesort import mergesort


if __name__ == "__main__":
    runtime = []
    results = []
    print "####################################################"
    data = [1, 100, 5, 2, 50, 25]
    print("Data: " + str(data))
    time1 = clock()
    result = mergesort(data, 0, len(data) - 1)
    time2 = clock()
    print "runtime: ", time2 - time1
    runtime.append(time2 - time1)
    output = compare_arr_sorted_equal(data, result)
    results.append(output)
    print "####################################################"
    data = [1, 100, 1000, 55, 500, 504, 23, 4, 3, 23, 45]
    print("Data: " + str(data))
    time1 = clock()
    result = mergesort(data, 0, len(data) - 1)
    time2 = clock()
    print "runtime: ", time2 - time1
    runtime.append(time2 - time1)
    output = compare_arr_sorted_equal(data, result)
    results.append(output)
Exemple #46
0
 def test_mergesort(self):
     self.assertListEqual(mergesort([6, 5, 3, 1, 8, 7, 2, 4]),
                          [1, 2, 3, 4, 5, 6, 7, 8])
Exemple #47
0
#!/usr/bin/python3

'''
A script to test quicksort, mergesort and bogosort
'''

import random
import quicksort
import mergesort
import bogosort
from sys import argv

data=[i for i in range(int(argv[-1]))]
random.shuffle(data)


if argv[-2]=='q':
    quicksort.quicksort(data)
elif argv[-2]=='m':
    mergesort.mergesort(data)
elif argv[-2]=='b':
    bogosort.bogosort(data)
Exemple #48
0
def main():
    # Aumenta o limite de recursão padrão
    sys.setrecursionlimit(10**6)

    # Flag que mantém o loop principal
    executando = True

    # Loop principal
    while executando:
        print("Digite o número do diretório:")
        print(" 1 |\t./1000/")
        print(" 2 |\t./2000/")
        print(" 3 |\t./3000/")
        print(" 4 |\t./5000/")
        print("   |")
        print(" 0 |\tSAIR DO PROGRAMA")
        folder = int(input())
        print()

        if folder == 0:
            print("FINALIZANDO EXECUÇÃO...")
            executando = False
            continue

        elif folder > 0 or folder < 5:
            print("Digite o numero do arquivo:")
            print(" 1 |\t./crescente.csv")
            print(" 2 |\t./decrescente.csv")
            print(" 3 |\t./random.csv")
            print("   |")
            print(" 0 |\tVOLTAR")
            file_index = int(input())
            print()

            if file_index == 0:
                continue
            elif file_index < 0 or file_index > 3:
                print("Opção inválida.")
            else:
                print("Digite a opção do algoritmo de ordenação")
                print(" 1 |\tInsertion Sort")
                print(" 2 |\tMerge Sort")
                print(" 3 |\tQuick Sort")
                print(" 4 |\tSelection Sort")
                print("   |")
                print(" 0 |\tMENU INICIAL")
                algo = int(input())
                print()

                if algo == 0:
                    continue
                elif algo < 0 or algo > 4:
                    print("Opção inválida")
                    continue
        else:
            print("Opção inválida.")

        file_name = "datasets_prontos/"

        if folder == 1:
            file_name += "1000/"
        elif folder == 2:
            file_name += "2000/"
        elif folder == 3:
            file_name += "3000/"
        else:
            file_name += "5000/"

        if file_index == 1:
            file_name += "crescente.csv"
        elif file_index == 2:
            file_name += "decrescente.csv"
        else:
            file_name += "random.csv"

        with open(Path(file_name)) as file:
            data = list(DictReader(file))
            tempo_total = 0

            if algo == 1:
                start_time = time.time()
                data = insertionsort.insertionsort(data)
                tempo_total = (time.time() - start_time)
            elif algo == 2:
                start_time = time.time()
                mergesort.mergesort(data, 0, len(data))
                tempo_total = (time.time() - start_time)
            elif algo == 3:
                start_time = time.time()
                Quick_Sort2.quicksort(data)
                tempo_total = (time.time() - start_time)

            else:
                start_time = time.time()
                selectionsort.selectionsort(data)
                tempo_total = (time.time() - start_time)

            header = data[0].keys()
            rows = [x.values() for x in data]
            print(
                "\n##############################################################################################"
            )
            print(tabulate(rows, header))
            print(
                "##############################################################################################\n"
            )
            print(
                "Concluído em {} segundos, com {} comparações e {} movimentações."
                .format(tempo_total, metrics.comp, metrics.mov))

        # Zera os valores das metricas
        metrics.resetmetrics()
 def test1(self):
     stimulus = [3, 2, 1]
     response = [1, 2, 3]
     self.assertEqual(response, mergesort(stimulus))
Exemple #50
0
#!/usr/bin/python3
from bubblesort import bubblesort
from heapsort import heapsort
from insertionsort import insertionsort
from mergesort import mergesort
from quicksort1 import quicksort1
from quicksort2 import quickSort2
from selectionsort import selectionsort
from shellsort import shellsort

bubblesort()
heapsort()
insertionsort()
mergesort()
quicksort1()
quickSort2()
selectionsort()
shellsort()
Exemple #51
0
		else:
			a[k] = b[j]
			j -= 1
		k -= 1
	if j > 0:
		a[:k+1] = b[:k+1]
	if j == 0:
		a[0] = b[0]
	return a


if __name__ == '__main__':
	a = [6,5,7,3,4,11,33,9,10]
	b = [-33, 6,9,8,5,-6,19]
	c = [-33, 6,99,8,6,-6]
	d = [0]
	e = []

	a_sorted = mergesort(a)
	b_sorted = mergesort(b)
	c_sorted = mergesort(c)
	d_sorted = mergesort(d)
	e_sorted = mergesort(e)

	print linear_merge(a_sorted, b_sorted)
	print linear_merge(a_sorted, c_sorted)
	print linear_merge(a_sorted, d_sorted)
	print linear_merge(a_sorted, e_sorted)
	print linear_merge(e_sorted, b_sorted)