Loading video…

heap sort

El Cato Instructor: El Cato

Description

import time
import random
import sys

# ---------------------------------------------------------
# Student Info [cite: 15-18]
# ---------------------------------------------------------
# Student Name: 
# ID: 
# Group#: 
# ---------------------------------------------------------

# ==========================================
# 1. Quicksort Implementation [cite: 53-73]
# ==========================================
def partition(arr, left, right):
    pivot = arr[left] # Choose first element as pivot [cite: 62]
    i = left
    
    for j in range(left + 1, right + 1):
        if arr[j] < pivot:
            i += 1
            arr[i], arr[j] = arr[j], arr[i]
            
    # Place pivot in correct position
    arr[left], arr[i] = arr[i], arr[left]
    return i

def quicksort(arr, left = None, right = None):
    if left is None: 
        left = 0

    if right is None: 
        right = len(arr) - 1

    if left < right:
        p = partition(arr, left, right)
        quicksort(arr, left, p - 1)
        quicksort(arr, p + 1, right)

def heapify(arr, n, i):
    largest = i
    left = 2 * i + 1
    right = 2 * i + 2
    
    # Check left child
    if left < n and arr[left] > arr[largest]:
        largest = left
        
    # Check right child
    if right < n and arr[right] > arr[largest]:
        largest = right
        
    # Swap and continue heapifying if root is not largest
    if largest != i:
        arr[i], arr[largest] = arr[largest], arr[i]
        heapify(arr, n, largest)

def heapsort(arr):
    n = len(arr)
    
    # Build a Max Heap
    for i in range(n // 2 - 1, -1, -1):
        heapify(arr, n, i)
        
    # Extract elements one by one
    for end in range(n - 1, 0, -1):
        arr[0], arr[end] = arr[end], arr[0]
        heapify(arr, end, 0)

def compare_sorts(arr: list):

    algorithms = [quicksort, heapsort]

    for algorithm in algorithms:
        copy = arr.copy()
        start = time.time()
        algorithm(copy)
        end = time.time()

        print(f'{algorithm.__name__} took {(end - start) * 1000}ms, result is: {copy}')


a = [12, 5, 9, 1, 14, 3, 7]
compare_sorts(a)

الملف حتى الان: https://t.me/c/2934627429/627

التتبع كامل: https://claude.ai/public/artifacts/605bf202-03a9-4532-b68f-cfdb7b112f7d

Comments

Log in to join the discussion. Log in