0% found this document useful (0 votes)
7 views1 page

Merge Sort Java

The document contains a Java program that implements the Merge Sort algorithm. It defines methods for merging two halves of an array and recursively sorting the array. The main method demonstrates sorting an example array and printing the sorted result.

Uploaded by

123456bca987
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views1 page

Merge Sort Java

The document contains a Java program that implements the Merge Sort algorithm. It defines methods for merging two halves of an array and recursively sorting the array. The main method demonstrates sorting an example array and printing the sorted result.

Uploaded by

123456bca987
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Sorting Program

public class MergeSort {


public static void merge(int[] arr, int l, int m, int r) {
int n1 = m - l + 1;
int n2 = r - m;

int[] L = new int[n1];


int[] R = new int[n2];

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


L[i] = arr[l + i];
for (int j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];

int i = 0, j = 0, k = l;
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++;
}
}

public static void mergeSort(int[] arr, int l, int r) {


if (l < r) {
int m = (l + r) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}

public static void main(String[] args) {


int[] arr = {38, 27, 43, 3, 9, 82, 10};
mergeSort(arr, 0, [Link] - 1);
for (int num : arr) {
[Link](num + " ");
}
}
}

You might also like