Exemple #1
0
    def test_bubble_sort(self):
        """
        Tests the bubble sort algorithm implementation.
        """

        collection = [5, 1, 10, 2, 16, 1]

        algorithms.bubble_sort(collection)

        # first, test that it actually worked and sorted the collection in place
        self.assertEqual(collection, [1, 1, 2, 5, 10, 16])

        # test that it works in the worst case scenario
        collection = [5, 4, 3, 2, 1]

        algorithms.bubble_sort(collection)

        self.assertEqual(collection, [1, 2, 3, 4, 5])

        # test that it works with strings
        collection = ['c', 'a', 'b']

        algorithms.bubble_sort(collection)

        self.assertEqual(collection, ['a', 'b', 'c'])

        # test worst case with 10 ints
        worst = [i for i in xrange(9, -1, -1)]

        algorithms.bubble_sort(worst)

        self.assertEqual([i for i in xrange(0, 10)], worst)
Exemple #2
0
    def test_insertion_sort(self):
        """
        Tests the insertion sort algorithm implementation.
        """
        collection = [5, 1, 10, 2, 16, 1]

        algorithms.insertion_sort(collection)

        self.assertEqual(collection, [1, 1, 2, 5, 10, 16])

        # test worst case with 10 ints
        collection = [i for i in xrange(9, -1, -1)]

        algorithms.bubble_sort(collection)

        self.assertEqual([i for i in xrange(0, 10)], collection)
def bubble_timer():
    # This is the function to time(in seconds) the bubble_sort algorithm.
    # Filename: 'bubble_timer_datapoints.txt'
    bp = open("bubble_timer_datapoints.txt", "w")
    for size in range(
            1, 201):  # 200 datapoints, each a list of 5000-15000 elements
        #for size in range(1, 2):	# range of 1-11 (10 lists[datapoints]) for testing
        alist = []
        for i in range(randint(5000, 15000)):
            alist.append(randint(1, 1000000))
        print("Starting bubble_sort on list #: {}\n".format(size))
        start_time = time()
        bubble_sort(alist)
        end_time = time()
        bubble_time = end_time - start_time
        bp.write("{},{}\n".format(len(alist), bubble_time))
        print("Finished bubble_sort'ing list #: {}\n".format(size))
Exemple #4
0
def test_bubble_sort_strings():
    assert bubble_sort([
        "C59OK", "5QV09", "TCNId", "ne58v", "ges28", "EzMbM", "qdPku", "ltinw",
        "Nt1Rj", "nSb8R"
    ]) == [
        "5QV09", "C59OK", "EzMbM", "Nt1Rj", "TCNId", "ges28", "ltinw", "nSb8R",
        "ne58v", "qdPku"
    ]
Exemple #5
0
def test_bubble_sort():
    answers = [
        ([], []),
        ([1], [1]),
        ([1, 9, 2, 8, 3, 7, 4, 6, 5], [1, 2, 3, 4, 5, 6, 7, 8, 9]),
        (
            ["abc", "cba", "aaa", "ccc", "bbb"],
            ["aaa", "abc", "bbb", "cba", "ccc"],
        ),
        ([6.42, 7.1, 1.4, 9.26, 6.4], [1.4, 6.4, 6.42, 7.1, 9.26]),
    ]
    for q, a in answers:
        assert bubble_sort(q) == a
Exemple #6
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
Exemple #7
0
def bucket_sort(array, bucket_size):
    if bucket_size < 1 or bucket_size > len(array):
        raise Exception("Incorrect bucket size")

    buckets_num = math.ceil(len(array) / bucket_size)
    buckets = [[] * buckets_num]
    max_elem = max(array)

    for elem in array:
        bucket_index = math.floor(elem / (max_elem * bucket_size))
        buckets[bucket_index].append(elem)

    for i in range(0, len(buckets)):
        buckets[i] = bubble_sort(buckets[i])

    return [bucket for bucket in buckets][0]
Exemple #8
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))])
Exemple #9
0
    pancake_process_time = ["Pancake Sort"]
    shell_process_time = ["Shell Sort"]
    entries = inputs.get_entries()
    for values in entries:

        # SELECTION SORT
        start = time.process_time()
        algorithms.selection_sort(entries[values][:])
        selection_process_time.append(time.process_time() - start)
        print(
            f"{selection_process_time[0]} processing time with {values} values: {time.process_time() - start}"
        )

        # BUBBLE SORT
        start = time.process_time()
        result = algorithms.bubble_sort(entries[values][:])
        bubble_process_time.append(time.process_time() - start)
        print(
            f"{bubble_process_time[0]} processing time with {values} values: {time.process_time() - start}"
        )

        # PANCAKE SORT
        start = time.process_time()
        result = algorithms.pancake_sort(entries[values][:])
        pancake_process_time.append(time.process_time() - start)
        print(
            f"{pancake_process_time[0]} processing time with {values} values: {time.process_time() - start}"
        )

        # SHELL SORT
        start = time.process_time()
 def test_bubble_sort_with_no_items(self):
   iterable = []
   algorithms.bubble_sort(iterable)
   expected = []
   self.assertEqual(iterable, expected)
Exemple #11
0
 def call_sort_method(self, random_list, max_vet, j):
     begin = time.time()
     bubble_sort(random_list)
     end = time.time()
     print('bubble sort with {} items vet[{}]: {} seconds'.format(max_vet, j + 1, end - begin))
     return end - begin
            sorting_method = button

            algorithms.delay = 1 if values[len(values) - 1] else 0

            # 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 test_bubble_sort():
    assert bubble_sort(ls1) == sorted(ls1)
    assert bubble_sort(ls2) == sorted(ls2)
    assert bubble_sort(ls3) == sorted(ls3)
    assert bubble_sort(ls4) == sorted(ls4)
    assert bubble_sort(ls5) == sorted(ls5)
Exemple #14
0
def test_it_sorts_a_list_of_numbers():
    list_unsorted = [9, 2, 1, 4, 8, 3, 5]
    bubble_sort(list_unsorted)

    assert list_unsorted == [1, 2, 3, 4, 5, 8, 9]
Exemple #15
0
def test_it_sorts_a_inverse_sorted_list_of_numbers():
    list_unsorted = [7, 6, 5, 4, 3, 2, 1]
    bubble_sort(list_unsorted)

    assert list_unsorted == [1, 2, 3, 4, 5, 6, 7]
Exemple #16
0
from algorithms import bubble_sort
from algorithms import selection_sort

x = [5, 6, 4, 3, 7, 8, 9, 0, 1, 2]
print("Import 1 for bubble sort algorithms")
print("Import 2 for selection sort algorithms")
n = int(input("Which algorithms you want to use:"))

if n == 1:
    bubble_sort(x)
if n == 2:
    selection_sort(x)

print(x)
 def test_bubble_sort_with_none_iterable_raises_type_error(self):
   iterable = None
   with self.assertRaises(TypeError):
     algorithms.bubble_sort(iterable)
Exemple #18
0
        except:
            print(
                f"Invalid number was entered, select a number between {min_num} and {max_num}. Try again!"
            )


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

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)
 def test_bubble_sort_is_stable_1(self):
   iterable = [[1], [1], [1], [1]]
   ids = [id(item) for item in iterable]
   algorithms.bubble_sort(iterable)
   expected = [id(item) for item in iterable]
   self.assertEqual(ids, expected)
Exemple #20
0
from algorithms import bubble_sort
from branch_predictor import BranchPredictor

history_lengths = list(range(2, 26, 2))
accuracies = collections.defaultdict(list)
movings_accs = collections.defaultdict(list)

input = list(range(10))

for i in history_lengths:

    bp = BranchPredictor(i)
    for _ in range(200):
        random.shuffle(input)
        bubble_sort(input, bp)

    accs, movings = bp.get_accuracies()
    for key in accs:
        accuracies[key].append(accs[key])
    for key in movings:
        movings_accs[key].append(movings[key])

plt.figure()

plt.subplot(1, 2, 1)
for key in accuracies:
    plt.plot(history_lengths, accuracies[key], label=key)
plt.legend()
plt.title("Overall Accuracy")
 def test_bubble_sort_with_one_item(self):
   iterable = [1]
   algorithms.bubble_sort(iterable)
   expected = [1]
   self.assertEqual(iterable, expected)
Exemple #22
0
def test_it_sorts_a_list_of_numbers_with_duplicates():
    list_unsorted = [7, 7, 5, 4, 3, 3, 1]
    bubble_sort(list_unsorted)

    assert list_unsorted == [1, 3, 3, 4, 5, 7, 7]
 def test_bubble_sort_with_two_items_2(self):
   iterable = [2, 1]
   algorithms.bubble_sort(iterable)
   expected = [1, 2]
   self.assertEqual(iterable, expected)
import random
import collections

import matplotlib.pyplot as plt

from algorithms import bubble_sort
from branch_predictor import BranchPredictor, TruePerceptron
import plotter

history_length = 64
bp = BranchPredictor(history_length, TruePerceptron)

data = list(range(64))

# for _ in range(history_length):
#     random.shuffle(data)
#     result, result_length = select(data, 0, 100, 16, bp)

iters = []
for _ in range(3):
    random.shuffle(data)
    bubble_sort(data, bp)
    iters.append(len(bp.prediction_history["flip"]))

bp.print_accuracies()

plotter.generate_plot_sort(bp, "flip", iters, 200)
 def test_bubble_sort_with_three_items_6(self):
   iterable = [3, 2, 1]
   algorithms.bubble_sort(iterable)
   expected = [1, 2, 3]
   self.assertEqual(iterable, expected)
def test_bubble_sort():
    assert bubble_sort([]) == []
    assert bubble_sort([2]) == [2]
    assert bubble_sort([3, 5, 6, 7, 4, 2]) == sorted([3, 5, 6, 7, 4, 2])
    assert bubble_sort([7, 4, 5, 3, 2, 6]) == sorted([7, 4, 5, 3, 2, 6])
 def test_bubble_sort_with_descending_items(self):
   iterable = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
   algorithms.bubble_sort(iterable)
   expected = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   self.assertEqual(iterable, expected)
 def test_insertion_sort_is_not_stable(self):
   iterable = [[3], [2], [3], [1]]
   ids = [id(item) for item in iterable if item[0] == 1]
   algorithms.bubble_sort(iterable)
   expected = [id(item) for item in iterable if item[0] == 1]
   self.assertEqual(ids, expected)
 def test_bubble_sort_with_strings(self):
   iterable = ['a', 's', 'd', 'f']
   algorithms.bubble_sort(iterable)
   expected = ['a', 'd', 'f', 's']
   self.assertEqual(iterable, expected)
Exemple #30
0

if __name__ == '__main__':
    test_elements = [10, 100, 1000, 10000, 100000, 300000]

    print(
        f'\nComparing algorithms for {len(test_elements)} lists with different lengths:\n'
    )

    for elements in test_elements:
        list_unsorted = generate_list(elements, MIN_VALUE, MAX_VALUE)

        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(
Exemple #31
0
def test_bubble_sort_numbers():
    assert bubble_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]