Heapsort uses a heap data structure to sort elements in O(n log n) time. It works by first building a max heap from the input elements and then repeatedly extracting the maximum element and reheapifying to put the next maximum into the root. This produces a sorted output in descending order. The heap property ensures that the root always contains the maximum element, allowing efficient extraction and replacement during the sorting process.