예제 #1
0
def quicksort(x):
    #Extended Quicksort with Insertion sort when length is lower of equal than 7
    n = len(x)
    if n == 0:
        return []
    if n == 1:
        return x
    if n <= 16:
        return insertion_sort(x)
    lower = []
    higheq = []
    eq = []
    pivot = insertion_sort([x[0], x[len(x) // 2], x[-1]])[1]
    for i in x:
        if i > pivot:
            higheq.append(i)
        elif i < pivot:
            lower.append(i)
        else:
            eq.append(i)
    newarr = []
    newarr.extend(quicksort(lower))
    newarr.extend(eq)
    newarr.extend(quicksort(higheq))
    return newarr
예제 #2
0
def start_algorithm():
    global data
    if not data: return 

    if(alg_menu.get() == 'Quick sort'):
        quick_sort(data, 0,len(data) - 1,draw_data,speed_scale.get())
    elif alg_menu.get() == 'Bubble sort':
        bubble_sort(data,draw_data,speed_scale.get())
    elif alg_menu.get() == 'Merge sort':
        merge_sort(data, draw_data, speed_scale.get())
    elif alg_menu.get() == 'Insertion sort':
        insertion_sort(data, draw_data, speed_scale.get())
    draw_data(data,[['green'] for x in range(len(data))])
예제 #3
0
def main():
    list_1 = random.sample(range(200000000), 100000)
    t_1 = time.time()
    bubble_sort(list_1)
    t_2 = time.time()
    print("bubble_sort_took", t_2 - t_1)
    t_1 = time.time()
    merge_sort(list_1, 0, 3)
    t_2 = time.time()
    print("merge_sort_took", t_2 - t_1)
    t_1 = time.time()
    merge_sort_without(list_1, 0, 3)
    t_2 = time.time()
    print("merge_sort_without_sentinel_took", t_2 - t_1)
    t_1 = time.time()
    insertion_sort(list_1)
    t_2 = time.time()
    print("insertion_sort", t_2 - t_1)
def start():
    print('Sorting...')
    global data
    if not data:
        return

    # These if else statements call the function of the selected algorithm
    if algMenu.get() == 'Quick Sort':
        quick_sort(data, draw_data, speedScale.get())
    elif algMenu.get() == 'Bubble Sort':
        bubble_sort(data, draw_data, speedScale.get())
    elif algMenu.get() == 'Insertion Sort':
        insertion_sort(data, draw_data, speedScale.get())
    elif algMenu.get() == 'Selection Sort':
        selection_sort(data, draw_data, speedScale.get())
    elif algMenu.get() == 'Merge Sort':
        merge_sort(data, 0, len(data) - 1, draw_data, speedScale.get())
    elif algMenu.get() == 'Counting Sort':
        count_sort(data, draw_data, speedScale.get())
예제 #5
0
    def test_insert_sort(self):
        unsorted1 = [1, 5, 8, 4, 2, 9, 6, 0, 3, 7]
        unsorted2 = []
        unsorted3 = [1, 5, -2, 4, 3]
        unsorted4 = random.sample(range(200), 50)

        self.assertEqual(insertion_sort(unsorted1), [0,1,2,3,4,5,6,7,8,9])
        self.assertEqual(insertion_sort(unsorted2), [])
        self.assertEqual(insertion_sort(unsorted3), [-2, 1, 3, 4, 5])
        self.assertEqual(insertion_sort(unsorted4), sorted(unsorted4))


# if __name__ == '__main__':
#     unittest.main()

# seems like if I manually call the unittest module I need to be
# within same dir
# whereas if I use unittest.main() within the test_file
# I can run it wherever
예제 #6
0
파일: bucket_sort.py 프로젝트: jtula/crls
def bucket_sort(a):
    '''
    Bucket sort (CLRS, pag. 200).
    Time complexity: O(n^2)
    Space complexity: O(n)
    '''
    n = len(a)
    b = [None] * n
    r = []

    for i in range(n):
        b[i] = []

    for i in range(n):
        b[math.floor(n * a[i])].append(a[i])

    for i in range(n - 1):
        insertion_sort(b[i])

    for k in b:
        for m in k:
            r.append(m)

    return r
예제 #7
0
def bucket_sort(unsorted_list, total_buckets):
  from insertion_sort import *

  current_max = None
  for value in unsorted_list:
    if value > current_max: current_max = value

  # Weird way to round up an integer without needing external libraries
  bucket_bounds = int(current_max / total_buckets) + (current_max % total_buckets > 0)
  buckets = [[] for x in range(0, total_buckets)]

  for number in unsorted_list:
    if number is 0:
      buckets[0].append(number)
    else:
      buckets[((number - 1)/bucket_bounds)].append(number)
  
  sorted_list = []
  for bucket in buckets:
    sorted_list += insertion_sort(bucket)

  return sorted_list
예제 #8
0
def bucket_sort(unsorted_list, total_buckets):
    from insertion_sort import *

    current_max = None
    for value in unsorted_list:
        if value > current_max: current_max = value

    # Weird way to round up an integer without needing external libraries
    bucket_bounds = int(
        current_max / total_buckets) + (current_max % total_buckets > 0)
    buckets = [[] for x in range(0, total_buckets)]

    for number in unsorted_list:
        if number is 0:
            buckets[0].append(number)
        else:
            buckets[((number - 1) / bucket_bounds)].append(number)

    sorted_list = []
    for bucket in buckets:
        sorted_list += insertion_sort(bucket)

    return sorted_list
예제 #9
0
 def test_02_return_none(self):
     self.assertEqual(None, insertion_sort([2]))
예제 #10
0
from datetime import datetime
from insertion_sort import *
from merge_sort import *
from bubble_sort import *

N = 4000

values = [int(random() * N * 1000) for y in range(N)]
t1 = datetime.now()
bubble_sort(values)
t2 = datetime.now()
print("bubble sort time:   ", (t2 - t1).total_seconds() * 1000)

values = [int(random() * N * 1000) for y in range(N)]
t1 = datetime.now()
insertion_sort(values)
t2 = datetime.now()
print("insert sort time:   ", (t2 - t1).total_seconds() * 1000)

values = [int(random() * N * 1000) for y in range(N)]
t1 = datetime.now()
merge_sort(values, 0, len(values) - 1)
t2 = datetime.now()
print("merge sort time:   ", (t2 - t1).total_seconds() * 1000)

values_benchmark = [int(random() * N) for y in range(N)]
t1 = datetime.now()
values_sorted = sorted(values_benchmark)
t2 = datetime.now()
print("builin sorted time:   ", (t2 - t1).total_seconds() * 1000)
 def test_insertion_sort_single_element(self):
     self.assertEqual(insertion_sort([1]), [1])
예제 #12
0
def test_insertion_sort():
    unsorted_arr = [1, 5, 7, 3, 2]
    assert insertion_sort(unsorted_arr) == [1, 2, 3, 5, 7]
def test_sort_empty():
    array = []
    actual = insertion_sort(array)
    expected = 'cannot sort an empty array'
    assert actual == expected
print()

print("Selection sorted: ")
selection_sorted_list = list(original)
a = time.time()
selection_sort(selection_sorted_list)
b = time.time()
print(b - a)
print_list(selection_sorted_list)
test_properties(sorted, selection_sorted_list)
print()

print("Insertion sorted: ")
insertion_sorted_list = list(original)
a = time.time()
insertion_sort(insertion_sorted_list)
b = time.time()
print(b - a)
print_list(insertion_sorted_list)
test_properties(sorted, insertion_sorted_list)
print()

print('Radix sorted: ')
binary_radix_sorted_list = list(original)
a = time.time()
binary_radix_sorted_list = binary_radix_sort(binary_radix_sorted_list)
b = time.time()
print(b - a)
print_list(binary_radix_sorted_list)
test_properties(sorted, binary_radix_sorted_list)
print()
예제 #15
0
from heap_sort import *


if __name__ == "__main__":

  buckets = 3

  all_lists = {}
  all_lists['ALREADY_SORTED'] = [1, 2, 4, 4, 6, 6, 8, 9]
  all_lists['REVERSE_SORTED'] = [9, 8, 6, 6, 4, 4, 2, 1]
  all_lists['FEW_UNIQUE'] = [3, 6, 6, 4, 3, 3, 3, 6, 6, 4]
  all_lists['RANDOM_ORDER'] = [2, 6, 4, 8, 1, 4, 6, 9]
  all_lists['BIG_RANGE'] = [170, 45, 75, 90, 802, 2, 24, 66]
  all_lists['LONG_LIST'] = [2,4,3,3,6,7,876,2,4,8,214,7,2,7,4,8,2,7,4,6,83,2,6,7,88,75,2,3,6,789,86,3,6,6,3,575,6,87,8,574]
  all_lists['ZEROES_IN_LIST'] = [9,0,3,0,54,6,1,45,1,57,1,56,8,8,3,0]
  all_lists['ALL_SAME_NUMBER'] = [7,7,7,7,7,7,7,7,7,7,7]


  for list_name, number_list in all_lists.iteritems():
    print "\nUSING LIST \n\t%s\n\t%s" %(list_name, number_list)
    
    print "Insertion sorted output: \n\t", insertion_sort(number_list)
    print "Bubble sorted output: \n\t", bubble_sort(number_list)
    print "Selection sorted output: \n\t", selection_sort(number_list)
    print "Bucket sorted output (using insertion sort and %s buckets): \n\t" %(buckets), bucket_sort(number_list, 3)
    print "Counting sorted output: \n\t", counting_sort(number_list)
    print "Quick sorted output: \n\t", quicksort(number_list)
    print "Merge sorted output: \n\t", mergesort(number_list)
    print "Radix sorted output (using counting sort): \n\t", radix_sort(number_list)
    print "Heap sorted output: \n\t", heapsort(number_list)
    
예제 #16
0
import random
import copy
from insertion_sort import *
from merge_sort import *
from quick_sort import *

if __name__ == "__main__":
  arr = [random.randint(0, 100) for i in range(10)]
  print(arr)
  print(insertion_sort(copy.deepcopy(arr)))
  print(arr)
  print(merge_sort(copy.deepcopy(arr)))
  print(arr)
  print(quick_sort(copy.deepcopy(arr), 0, len(arr)-1))
예제 #17
0
 def test_01_zero_elements(self):
     v = []
     insertion_sort(v)
     self.assertEqual(v, [])
예제 #18
0
 def test_06_piccinno_list(self):
     v = [23, 34, 55, 32, 7777, 98, 3, 2, 1]
     insertion_sort(v)
     vcopy = v[:]
     vcopy.sort()
     self.assertEqual(v, vcopy)
예제 #19
0
 def test_05_three_elements(self):
     v = [2, 1, 3]
     insertion_sort(v)
     self.assertEqual(v, [1, 2, 3])
예제 #20
0
 def test_04_two_elements(self):
     v = [2, 1]
     insertion_sort(v)
     self.assertEqual(v, [1, 2])
예제 #21
0
 def test_03_one_element(self):
     v = ["a"]
     insertion_sort(v)
     self.assertEqual(v, ["a"])
예제 #22
0
파일: sort.py 프로젝트: abendory/python
#!/usr/bin/python3

from bubble_sort import *
from insertion_sort import *
from selection_sort import *
from qsort import *

alist = [54,26,93,17,77,31,44,55,20]
print(alist)
bubble_sort(alist)
print(alist)

alist = [54,26,93,17,77,31,44,55,20]
print(alist)
selection_sort(alist)
print(alist)

alist = [54,26,93,17,77,31,44,55,20]
print(alist)
insertion_sort(alist)
print(alist)

alist = [54,26,93,17,77,31,44,55,20]
print(alist)
qsort(alist)
print(alist)
예제 #23
0
파일: sort.py 프로젝트: addie/python
#!/usr/bin/python3

from bubble_sort import *
from insertion_sort import *
from selection_sort import *
from qsort import *

alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print(alist)
bubble_sort(alist)
print(alist)

alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print(alist)
selection_sort(alist)
print(alist)

alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print(alist)
insertion_sort(alist)
print(alist)

alist = [54, 26, 93, 17, 77, 31, 44, 55, 20]
print(alist)
qsort(alist)
print(alist)
예제 #24
0
 def test_zero_input(self):
     data = []
     insertion_sort(data)
     self.assertEqual(data, [])
예제 #25
0
    all_lists = {}
    all_lists['ALREADY_SORTED'] = [1, 2, 4, 4, 6, 6, 8, 9]
    all_lists['REVERSE_SORTED'] = [9, 8, 6, 6, 4, 4, 2, 1]
    all_lists['FEW_UNIQUE'] = [3, 6, 6, 4, 3, 3, 3, 6, 6, 4]
    all_lists['RANDOM_ORDER'] = [2, 6, 4, 8, 1, 4, 6, 9]
    all_lists['BIG_RANGE'] = [170, 45, 75, 90, 802, 2, 24, 66]
    all_lists['LONG_LIST'] = [
        2, 4, 3, 3, 6, 7, 876, 2, 4, 8, 214, 7, 2, 7, 4, 8, 2, 7, 4, 6, 83, 2,
        6, 7, 88, 75, 2, 3, 6, 789, 86, 3, 6, 6, 3, 575, 6, 87, 8, 574
    ]
    all_lists['ZEROES_IN_LIST'] = [
        9, 0, 3, 0, 54, 6, 1, 45, 1, 57, 1, 56, 8, 8, 3, 0
    ]
    all_lists['ALL_SAME_NUMBER'] = [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]

    for list_name, number_list in all_lists.iteritems():
        print "\nUSING LIST \n\t%s\n\t%s" % (list_name, number_list)

        print "Insertion sorted output: \n\t", insertion_sort(number_list)
        print "Bubble sorted output: \n\t", bubble_sort(number_list)
        print "Selection sorted output: \n\t", selection_sort(number_list)
        print "Bucket sorted output (using insertion sort and %s buckets): \n\t" % (
            buckets), bucket_sort(number_list, 3)
        print "Counting sorted output: \n\t", counting_sort(number_list)
        print "Quick sorted output: \n\t", quicksort(number_list)
        print "Merge sorted output: \n\t", mergesort(number_list)
        print "Radix sorted output (using counting sort): \n\t", radix_sort(
            number_list)
        print "Heap sorted output: \n\t", heapsort(number_list)
예제 #26
0
 def test_single_input(self):
     data = rand_list(count=1)
     data_cp = data[:]
     insertion_sort(data)
     self.assertEqual(data, data_cp)
def test_sort_dupes():
    array = [8,4,4,4,16,5]
    actual = insertion_sort(array)[0]
    expected = [4,4,4,5,8,16]
    assert actual == expected
예제 #28
0
 def test_double_input(self):
     data = rand_list(count=2)
     insertion_sort(data)
     self.assertLessEqual(data[0], data[1])
def test_sort_happy():
    array = [8,4,23,42,16,15]
    actual = insertion_sort(array)[0]
    expected = [4,8,15,16,23,42]
    assert actual == expected
예제 #30
0
import random
from insertion_sort import *
from selection_sort import *
from merge_sort import *

my_randoms = random.sample(range(1, 100000000), 1000)

print(my_randoms)

print(insertion_sort(my_randoms))
selection_sort(my_randoms)
selection_sort_2(my_randoms)
print(merge_sort(my_randoms))
 def test_insertion_sort_empty_array(self):
     self.assertEqual(insertion_sort([]), [])
예제 #32
0
 def test_insertion_sort(self):
     self.assertEqual(insertion_sort([5, 2, 4, 6, 1, 3]),
                      [1, 2, 3, 4, 5, 6])
     self.assertEqual(insertion_sort([5]), [5])
     self.assertEqual(insertion_sort([]), [])
     self.assertEqual(insertion_sort([1, 5, 2, 1, 6]), [1, 1, 2, 5, 6])
 def test_insertion_sort_with_elements(self):
     self.assertEqual(insertion_sort([1, 5, 8, 3, 5, 9]),
                      [1, 3, 5, 5, 8, 9])
     self.assertEqual(insertion_sort([9, 15, 1, 85, 74, 789, 1111, 3, 365]),
                      [1, 3, 9, 15, 74, 85, 365, 789, 1111])
예제 #34
0
 def test_all_same_input(self):
     single_val = rand_list(count=1)[0]
     data = [single_val]*100
     insertion_sort(data)
     for i in range(0, 100):
         self.assertEqual(single_val, data[i])
예제 #35
0
 def test_array_input(self):
     data = rand_list()
     insertion_sort(data)
     for i in range(1, len(data)):
         self.assertLessEqual(data[i-1], data[i])
예제 #36
0
values = range(1,10)
random.shuffle(values)
values[:]

print "List to be sorted is {0}".format(values)
print "-" * 30
print "Selection Sort"
print "-" * 30
values1 = values[:]
selection_sort(values1)
print "-" * 30
print "Insertion Sort"
print "-" * 30
values2 = values[:]
insertion_sort(values2)
print "-" * 30
print "Bubble Sort"
print "-" * 30
values3 = values[:]
bubble_sort(values3)
print "-" * 30
print "Comb Sort"
print "-" * 30
values4 = values[:]
comb_sort(values4)
print "-" * 30
print "Shell Sort"
print "-" * 30
values5 = values[:]
shell_sort(values5)
예제 #37
0
 def test_all_zero_input(self):
     data = [0]*100
     insertion_sort(data)
     for i in range(0, 100):
         self.assertEqual(data[i], 0)
예제 #38
0
            n = int(input('\n\n Aperte 0 Para Voltar: '))

    elif n == 4:
        print("\n" * 130)
        print('*** Insertion Sort ***\n')
        try:
            nome_arq = input('Nome do arquivo a ser Aplicado Insertion Sort: ')
            nome_arq = nome_arq + '.txt'
            arquivo = open(nome_arq, 'r')
            lista = arquivo.readlines()
            x3 = 0
            while x3 != 9:
                for index in range(len(lista)):
                    lista[index] = lista[index].rstrip('\n')
                    lista[index] = int(lista[index])
                insertion_sort(lista)
                n_lista = lista
                print('*** Aplicado o Insertion Sort ***\n')
                print(lista)
                arquivo = open(nome_arq, "w")
                frases = list()
                for i in range(len(n_lista)):
                    frases.append(str(n_lista[i]))
                    frases.append('\n')
                arquivo.writelines(frases)
                arquivo.close()
                x3 = int(input('\n\n Aperte 9 Para Voltar: '))

        except FileNotFoundError:
            print('Arquivo não Foi encontrado ')
            print('Erros Provaveis: Nome errado')