You are on page 1of 8

МІНІСТЕРСТВО ОСВІТИ І НАУКИ УКРАЇНИ

ЗАПОРІЗЬКИЙ НАЦІОНАЛЬНИЙ УНІВЕРСИТЕТ


МАТЕМАТИЧНИЙ ФАКУЛЬТЕТ
КАФЕДРА ПРОГРАМНОЇ ІНЖЕНЕРІЇ

Дисципліна «Практикум програмування»


Лабораторна робота № 10

Виконав студент гр. 6.1210-2пі


Новіков Олег

Перевірив: Викладач
Мухін Віталій Вікторович

Запоріжжя
2022
Хід роботи
Завдання
Використовуючи Selections sort відсортуєте заданий масив 6 1 9 13 5 44 35 8.
Теоретичний матеріал
Сортування вибором — простий алгоритм сортування лінійного масиву,
на основі вставок. Має ефективність n2, що робить його неефективним при
сортування великих масивів, і в цілому, менш ефективним за подібний
алгоритм сортування включенням. Сортування вибором вирізняється більшою
простотою, ніж сортування включенням, і в деяких випадках, вищою
продуктивністю
Алгоритм
Алгоритм працює таким чином:

1. Знаходить у списку найменше значення


2. Міняє його місцями із першим значенням у списку
3. Повторює два попередніх кроки, доки список не завершиться (починаючи з
наступної позиції)
Фактично, таким чином ми поділили список на дві частини: перша (ліва) —
повністю відсортована, а друга (права) — ні.
Код
import random
import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation

def swap(A, i, j):


    """Helper function to swap elements i and j of list A."""

    if i != j:
        A[i], A[j] = A[j], A[i]

def bubblesort(A):
    """In-place bubble sort."""

    if len(A) == 1:
        return

    swapped = True
    for i in range(len(A) - 1):
        if not swapped:
            break
        swapped = False
        for j in range(len(A) - 1 - i):
            if A[j] > A[j + 1]:
                swap(A, j, j + 1)
                swapped = True
            yield A

def selectionsort(A):
    """In-place selection sort."""
    if len(A) == 1:
        return

    for i in range(len(A)):
        minVal = A[i]
        minIdx = i
        for j in range(i, len(A)):
            if A[j] < minVal:
                minVal = A[j]
                minIdx = j
            yield A
        swap(A, i, minIdx)
        yield A

if __name__ == "__main__":
    N = int(input("Enter number of integers: "))
    method_msg = "Enter sorting method:\n(b)ubble\n(s)election\n"
    method = input(method_msg)

    # Build and randomly shuffle list of integers.


    A = [x + 1 for x in range(N)]
    random.seed(time.time())
    random.shuffle(A)
    print('Shuffle list: ', A)
    B  = A[::]

    # Get appropriate generator to supply to matplotlib FuncAnimation method.


    if method == "b":
        title = "Bubble sort"
        generator = bubblesort(A)
       
    else:
        title = "Selection sort"
        generator = selectionsort(A)
       

    # Initialize figure and axis.


    fig, ax = plt.subplots()
    ax.set_title(title)

    # Initialize a bar plot. Note that matplotlib.pyplot.bar() returns a


    # list of rectangles (with each bar in the bar plot corresponding
    # to one rectangle), which we store in bar_rects.
    bar_rects = ax.bar(range(len(A)), A, align="edge")

    # Set axis limits. Set y axis upper limit high enough that the tops of
    # the bars won't overlap with the text label.
    ax.set_xlim(0, N)
    ax.set_ylim(0, int(1.07 * N))

    # Place a text label in the upper-left corner of the plot to display


    # number of operations performed by the sorting algorithm (each "yield"
    # is treated as 1 operation).
    text = ax.text(0.02, 0.95, "", transform=ax.transAxes)

    iteration = [0]
   

    def update_fig(A, rects, iteration):


        for rect, val in zip(rects, A):
            rect.set_height(val)
        iteration[0] += 1
        text.set_text("# of operations: {}".format(iteration[0]))

    anim = animation.FuncAnimation(fig, func=update_fig,


        fargs=(bar_rects, iteration), frames=generator, interval=1,
        repeat=False)
    plt.show()
    with open('res.txt', 'w') as file:
        if method == "b":
            gen = bubblesort(B)
        else:
            gen =  selectionsort(B)
        for i in gen:
            file.write(f'Step: {i}\n')
   
Результат роботи

You might also like