Skip to content
This repository has been archived by the owner on Oct 14, 2021. It is now read-only.

Commit

Permalink
Merge Sort in java (#540)
Browse files Browse the repository at this point in the history
  • Loading branch information
sparshsukralia authored Oct 12, 2021
1 parent 565d94f commit 72517e7
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions Programming/Java/MergeSort/MergeSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package Programming.Java.MergeSort;

public class MergeSort {

public static void merge(int[] arr, int l, int mid, int r) {
int[] b = new int[arr.length];
int i = l;
int j = mid + 1;
int k = l;
while (i <= mid && j <= r) {
if (arr[i] < arr[j]) {
b[k] = arr[i];
i++;
} else {
b[k] = arr[j];
j++;
}
k++;
}
if (i > mid) {
while (j <= r) {
b[k] = arr[j];
k++;
j++;
}
} else {
while (i <= mid) {
b[k] = arr[i];
k++;
i++;
}
}
for (k = l; k <= r; k++) {
arr[k] = b[k];
}
}

public static void mergeSort(int[] arr, int l, int r) {
if (l < r) {
int mid = (l + r) / 2;
mergeSort(arr, l, mid);
mergeSort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
}

public static void main(String[] args) {
int[] arr = { 73, 188, 894, 915, 940, 616, 900, 548 };
mergeSort(arr, 0, arr.length - 1);
for (int j : arr)
System.out.print(j + " ");
}
}

0 comments on commit 72517e7

Please sign in to comment.