Blog Pages

Algorithm Performance Visualizer

import random

import time

import matplotlib.pyplot as plt


# --------------------------------------

# Sorting Algorithms

# --------------------------------------


def bubble_sort(arr):

    arr = arr.copy()

    n = len(arr)

    for i in range(n):

        for j in range(0, n - i - 1):

            if arr[j] > arr[j + 1]:

                arr[j], arr[j + 1] = arr[j + 1], arr[j]

    return arr



def insertion_sort(arr):

    arr = arr.copy()

    for i in range(1, len(arr)):

        key = arr[i]

        j = i - 1

        while j >= 0 and key < arr[j]:

            arr[j + 1] = arr[j]

            j -= 1

        arr[j + 1] = key

    return arr



def merge_sort(arr):

    if len(arr) <= 1:

        return arr


    mid = len(arr) // 2

    left = merge_sort(arr[:mid])

    right = merge_sort(arr[mid:])


    return merge(left, right)



def merge(left, right):

    result = []

    i = j = 0


    while i < len(left) and j < len(right):

        if left[i] < right[j]:

            result.append(left[i])

            i += 1

        else:

            result.append(right[j])

            j += 1


    result.extend(left[i:])

    result.extend(right[j:])

    return result



def quick_sort(arr):

    if len(arr) <= 1:

        return arr

    pivot = arr[len(arr) // 2]

    left = [x for x in arr if x < pivot]

    middle = [x for x in arr if x == pivot]

    right = [x for x in arr if x > pivot]

    return quick_sort(left) + middle + quick_sort(right)



# --------------------------------------

# Benchmark Function

# --------------------------------------


def measure_time(func, arr):

    start = time.time()

    func(arr)

    end = time.time()

    return end - start



# --------------------------------------

# Main Visualization

# --------------------------------------


if __name__ == "__main__":

    sizes = [100, 500, 1000, 2000]

    results = {

        "Bubble Sort": [],

        "Insertion Sort": [],

        "Merge Sort": [],

        "Quick Sort": []

    }


    for size in sizes:

        print(f"Testing size: {size}")

        data = [random.randint(1, 10000) for _ in range(size)]


        results["Bubble Sort"].append(measure_time(bubble_sort, data))

        results["Insertion Sort"].append(measure_time(insertion_sort, data))

        results["Merge Sort"].append(measure_time(merge_sort, data))

        results["Quick Sort"].append(measure_time(quick_sort, data))


    # Plot Results

    plt.figure(figsize=(10, 6))


    for algo, times in results.items():

        plt.plot(sizes, times, marker='o', label=algo)


    plt.xlabel("Input Size")

    plt.ylabel("Execution Time (seconds)")

    plt.title("Sorting Algorithm Performance Comparison")

    plt.legend()

    plt.grid(True)

    plt.show()

No comments:

Post a Comment