0% found this document useful (0 votes)
3 views2 pages

Java Merge Sort Implementation

The document contains a Java implementation of the Merge Sort algorithm. It includes methods for merging two halves of an array and recursively sorting the array. The main method demonstrates sorting an example array and printing the original and sorted arrays.

Uploaded by

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

Java Merge Sort Implementation

The document contains a Java implementation of the Merge Sort algorithm. It includes methods for merging two halves of an array and recursively sorting the array. The main method demonstrates sorting an example array and printing the original and sorted arrays.

Uploaded by

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

public class MergeSort {

// Corrected the method signature for merge.

public static void merge(int[] a, int lb, int mid, int ub) {
int i = lb;
int j = mid + 1;
int k = lb;
int[] b = new int[[Link]]; // Added an array to store the merged result.

while (i <= mid && j <= ub) {


if (a[i] <= a[j]) { // Corrected the comparison operator.
b[k] = a[i];
i++;
} else {
b[k] = a[j];
j++;
}
k++;
}

while (i <= mid) {


b[k] = a[i];
i++;
k++;
}

while (j <= ub) {


b[k] = a[j];
j++;
k++;
}

// Copy the merged array back to the original array 'a'.


// for (int x = lb; x <= ub; x++) {
// a[x] = b[x];
// }
}

static void mergeSort(int[] sorted, int start, int end) {


if (start < end) {
int mid = (start + end) / 2;
mergeSort(sorted, start, mid);
mergeSort(sorted, mid + 1, end);
merge(sorted, start, mid, end);
}
}

public static void main(String[] args) {


int arr[] = {7, 6, 10, 5, 9, 2, 1, 15, 7};
int n = [Link];

[Link]("Original Array:");
printArray(arr);

[Link]("\nSorted Array:");
mergeSort(arr, 0, [Link] - 1);
printArray(arr);
}

public static void printArray(int[] arr) {


for (int value : arr) {
[Link](value + " ");
}
[Link]();
}
}

You might also like