Moment For Technology

Python heap sort

Posted on Aug. 9, 2023, 3:49 a.m. by Cole Salas
Category: The back-end Tag: The back-end

Reference: www.bilibili.com/video/BV1E4...

Python implementation

Def heapSort(arr): def heapSort(arr): def heapSort(arr): len(arr) = len(arr) AdjustHeap (arr, I, len(arr)) # swap the largest and last bits for j in range(len(arr) -1, 0, -1): Arr [0], arr[0] = arr[j], arr[0] adjustHeap(arr, 0, j) # {4,9,8,5,6} def arr[0] = arr[j], arr[0] adjustHeap(arr, 0, j) # {5, 9,8,5,6} Return: """ temp = arr[index] k = 2 * index + 1 while k  length: If k  length and arr[k]  arr[k + 1]: k += 1 if arr[k]  temp: arr[index] = arr[k] index = k else: arr[index] = arr[k] index = k else: break k = k * 2 + 1 arr[index] = temp l = [4, 9, 8, 5, 6, 11] heapSort(l) print(l)Copy the code
Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.