|
| 1 | +package sort |
| 2 | + |
| 3 | +/** |
| 4 | + * This function implements the Heap Sort. |
| 5 | + * |
| 6 | + * @param array The array to be sorted |
| 7 | + * Sorts the array in increasing order |
| 8 | + * |
| 9 | + * Worst-case performance O(n*log(n)) |
| 10 | + * Best-case performance O(n*log(n)) |
| 11 | + * Average-case performance O(n*log(n)) |
| 12 | + * Worst-case space complexity O(1) (auxiliary) |
| 13 | + */ |
| 14 | +fun <T: Comparable<T>> heapSort(array: Array<T>) { |
| 15 | + buildMaxHeap(array) |
| 16 | + transformMaxHeapToSortedArray(array) |
| 17 | +} |
| 18 | + |
| 19 | +/** |
| 20 | + * This function changes the element order of the array to represent a max |
| 21 | + * binary tree. |
| 22 | + * |
| 23 | + * @param array The array containing the elements |
| 24 | + * @param index Index of the currently largest element |
| 25 | + */ |
| 26 | +fun <T: Comparable<T>> maxheapify(array: Array<T>, heapSize: Int, index: Int) { |
| 27 | + val left = 2 * index + 1 |
| 28 | + val right = 2 * index + 2 |
| 29 | + var largest = index |
| 30 | + |
| 31 | + if(left < heapSize && array[left] > array[largest]) |
| 32 | + largest = left |
| 33 | + if(right < heapSize && array[right] > array[largest]) |
| 34 | + largest = right |
| 35 | + if(largest != index) { |
| 36 | + swapElements(array, index, largest) |
| 37 | + maxheapify(array, heapSize, largest) |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +/** |
| 42 | + * Arrange the elements of the array to represent a max heap. |
| 43 | + * |
| 44 | + * @param array The array containing the elements |
| 45 | + */ |
| 46 | +private fun <T: Comparable<T>> buildMaxHeap(array: Array<T>) { |
| 47 | + val n = array.size |
| 48 | + for(i in (n / 2 - 1) downTo 0) |
| 49 | + maxheapify(array, n, i) |
| 50 | +} |
| 51 | + |
| 52 | +/** |
| 53 | + * Arrange the elements of the array, which should be in order to represent a |
| 54 | + * max heap, into ascending order. |
| 55 | + * |
| 56 | + * @param array The array containing the elements (max heap representation) |
| 57 | + */ |
| 58 | +private fun <T: Comparable<T>> transformMaxHeapToSortedArray(array: Array<T>) { |
| 59 | + for(i in (array.size - 1) downTo 0) { |
| 60 | + swapElements(array, i, 0) |
| 61 | + maxheapify(array, i, 0) |
| 62 | + } |
| 63 | +} |
| 64 | + |
0 commit comments