📜  Big o heap sort - 任意(1)

📅  最后修改于: 2023-12-03 15:29:37.066000             🧑  作者: Mango

Big O Heap Sort

Heap Sort is a sorting algorithm that utilizes max heap data structure. It is a comparison based sorting algorithm that works by first creating a max heap from the input data. It then progressively swap the largest element to the end of the array until the whole array is sorted.

The time complexity for this algorithm is O(n * log n), making it quite efficient.

Here is an implementation of Big O Heap Sort in Python:

def heapify(arr, n, i):
    # Find the largest among root, left child and right child
    largest = i
    left = 2 * i + 1
    right = 2 * i + 2
    if left < n and arr[i] < arr[left]:
        largest = left
    if right < n and arr[largest] < arr[right]:
        largest = right
    
    # Swap if largest is not root
    if largest != i:
        arr[i], arr[largest] = arr[largest], arr[i]
        # Recursively heapify the affected sub-tree
        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)
    
    # One by one extract elements
    for i in range(n - 1, 0, -1):
        arr[i], arr[0] = arr[0], arr[i] # swap
        heapify(arr, i, 0)
        
    return arr

The heapify function takes an array, its length and a root index as input. It finds the largest element among root, left child and right child, then swaps it with the root if it is not already the root. The function is then recursively called on the affected sub-tree to maintain the max heap property.

The heapSort function builds a max heap, then repeatedly extracts the root element and swaps it with the last element before calling heapify on the remaining elements. This continues until the whole array is sorted.

Here is an example of the usage of the function:

arr = [64, 34, 25, 12, 22, 11, 90]
print("Original array:", arr)
arr = heapSort(arr)
print("Sorted array:", arr)

Output:

Original array: [64, 34, 25, 12, 22, 11, 90]
Sorted array: [11, 12, 22, 25, 34, 64, 90]

Overall, Big O Heap Sort is an efficient and effective sorting algorithm that can be used in a variety of situations.