Skip to content

Commit

Permalink
Implement merge sort in Java
Browse files Browse the repository at this point in the history
  • Loading branch information
dvir019 authored Oct 16, 2024
1 parent 361b534 commit c1bd4ab
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions Sorting/Java/MergeSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import java.util.Arrays;

class MergeSort {
private static void merge(int[] arr, int left, int middle, int right) {
int n1 = middle - left + 1;
int n2 = right - middle;

int[] leftArray = new int[n1];
int[] rightArray = new int[n2];

System.arraycopy(arr, left, leftArray, 0, n1);
for (int j = 0; j < n2; j++) {
rightArray[j] = arr[middle + 1 + j];
}

int i = 0, j = 0;

int k = left;
while (i < n1 && j < n2) {
if (leftArray[i] <= rightArray[j]) {
arr[k] = leftArray[i];
i++;
} else {
arr[k] = rightArray[j];
j++;
}
k++;
}

while (i < n1) {
arr[k] = leftArray[i];
i++;
k++;
}

while (j < n2) {
arr[k] = rightArray[j];
j++;
k++;
}
}

private static void mergeSort(int[] arr, int left, int right) {
if (left < right) {
int middle = (left + right) / 2;

mergeSort(arr, left, middle);
mergeSort(arr, middle + 1, right);

merge(arr, left, middle, right);
}
}

private static void mergeSort(int[] arr) {
mergeSort(arr, 0, arr.length - 1);
}

public static void main(String[] args) {
int[] arr = { 1, 5, 0, -8, 2, 1, 0, -2};

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

mergeSort(arr);

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

0 comments on commit c1bd4ab

Please sign in to comment.