public int[] heapSort(int[] A, int n) {
buildMaxHeap(A, lastIndex);
adjustHeap(A,0,lastIndex);
public void buildMaxHeap(int[] arr, int lastIndex) {
int j = (lastIndex - 1) / 2;
adjustHeap(arr, rootIndex, lastIndex);
public void adjustHeap(int[] arr, int rootIndex, int lastIndex) {
int biggerIndex = rootIndex;
int leftChildIndex = rootIndex * 2 + 1;
int rightChildIndex = rootIndex * 2 + 2;
if(rightChildIndex <= lastIndex){
if(arr[rightChildIndex] > arr[rootIndex] || arr[leftChildIndex] > arr[rootIndex]){
biggerIndex = arr[rightChildIndex] > arr[leftChildIndex]?rightChildIndex:leftChildIndex;
else if(leftChildIndex <= lastIndex){
if(arr[leftChildIndex] > arr[rootIndex]){
biggerIndex = leftChildIndex;
if(biggerIndex != rootIndex){
swap(arr, biggerIndex, rootIndex);
adjustHeap(arr, biggerIndex, lastIndex);
public void swap(int[] arr, int biggerIndex, int rootIndex) {
int temp = arr[rootIndex];
arr[rootIndex] = arr[biggerIndex];