Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

Experiment 10:

AIM:Write a java program to implement Merge & Heap Sort of given elements.

CODE:

import java.util.Arrays;

public class SortingAlgorithms {

// Merge Sort

public static void mergeSort(int[] arr) {

if (arr == null || arr.length <= 1) return;

mergeSortHelper(arr, 0, arr.length - 1);

private static void mergeSortHelper(int[] arr, int low, int high) {

if (low < high) {

int mid = low + (high - low) / 2;

mergeSortHelper(arr, low, mid);

mergeSortHelper(arr, mid + 1, high);

merge(arr, low, mid, high);

private static void merge(int[] arr, int low, int mid, int high) {

int n1 = mid - low + 1;

int n2 = high - mid;

int[] L = new int[n1];

int[] R = new int[n2];


for (int i = 0; i < n1; ++i)

L[i] = arr[low + i];

for (int j = 0; j < n2; ++j)

R[j] = arr[mid + 1 + j];

int i = 0, j = 0;

int k = low;

while (i < n1 && j < n2) {

if (L[i] <= R[j]) {

arr[k] = L[i];

i++;

} else {

arr[k] = R[j];

j++;

k++;

while (i < n1) {

arr[k] = L[i];

i++;

k++;

}
while (j < n2) {

arr[k] = R[j];

j++;

k++;

// Heap Sort

public static void heapSort(int[] arr) {

if (arr == null || arr.length <= 1) return;

int n = arr.length;

// Build heap (rearrange array)

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

heapify(arr, n, i);

// One by one extract an element from heap

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

// Move current root to end

int temp = arr[0];

arr[0] = arr[i];

arr[i] = temp;

// call max heapify on the reduced heap

heapify(arr, i, 0);
}

private 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 = {12, 11, 13, 5, 6, 7};


System.out.println("Original array: " + Arrays.toString(arr));

// Merge Sort

int[] arrMerge = arr.clone();

mergeSort(arrMerge);

System.out.println("After Merge Sort: " + Arrays.toString(arrMerge));

// Heap Sort

int[] arrHeap = arr.clone();

heapSort(arrHeap);

System.out.println("After Heap Sort: " + Arrays.toString(arrHeap));

OUTPUT:

Original array: [12, 11, 13, 5, 6, 7]

After Merge Sort: [5, 6, 7, 11, 12, 13]

After Heap Sort: [5, 6, 7, 11, 12, 13]

You might also like