var heapSort = function(arr) { buildMaxHeap(arr); for (var i = arr.length - 1; i > 0; i--) { swap(arr, 0, i); maxHeapify(arr, 0, i); } }; var buildMaxHeap = function(arr) { for (var i = (arr.length / 2 | 0) - 1; i >= 0; i--) { maxHeapify(arr, i, arr.length); } }; var maxHeapify = function(arr, i, size) { var l = 2 * i + 1, r = l + 1, maxIndex = i; if (l < size && arr[l] > arr[maxIndex]) { maxIndex = l; } if (r < size && arr[r] > arr[maxIndex]) { maxIndex = r; } if (maxIndex !== i) { swap(arr, i, maxIndex); maxHeapify(arr, maxIndex, size); } }; var swap = function(a, i, j) { var t = a[i]; a[i] = a[j]; a[j] = t; };