# CODE: import java.util.Arrays; public class Sorts { public static void heapSort(int[] arr) { int n

## Question:

CODE:

import java.util.Arrays;

public class Sorts {

public static void heapSort(int[] arr) {

int n = arr.length;

for (int i = n / 2 - 1; i >= 0; i--)

heapify(arr, n, i);

for (int i = n - 1; i >= 0; i--) {

int temp = arr[0];

arr[0] = arr[i];

arr[i] = temp;

heapify(arr, i, 0);

}

}

static void heapify(int[] arr, int n, int i) {

int largest = i;

int l = 2 * i + 1;

int r = 2 * i + 2;

if (l < n && arr[l] > arr[largest])

largest = l;

if (r < n && arr[r] > arr[largest])

largest = r;

if (largest != i) {

int swap = arr[i];

arr[i] = arr[largest];

arr[largest] = swap;

heapify(arr, n, largest);

}

}

public static void main(String[] args) {

int[] arr = { 4, 10, 3, 5, 1 };

System.out.println("Array before sorting: " + Arrays.toString(arr));

Sorts.heapSort(arr);

System.out.println("Array after sorting: "+Arrays.toString(arr));

}

}

**Related Book For**

## Introduction to Java Programming, Comprehensive Version

ISBN: 978-0133761313

10th Edition

Authors: Y. Daniel Liang

**View Solution**

**Cannot find your solution?**

**Question Details**

**8**

**Posted Date:**September 08, 2023 05:32:10