how to write a merge sort array method ni java
public static void merge(
int[] a, int[] l, int[] r, int left, int right) {
int i = 0, j = 0, k = 0;
while (i < left && j < right) {
if (l[i] <= r[j]) {
a[k++] = l[i++];
}
else {
a[k++] = r[j++];
}
}
while (i < left) {
a[k++] = l[i++];
}
while (j < right) {
a[k++] = r[j++];
}
}
public static void mergeSort(int[] a, int n) {
if (n < 2) {
return;
}
int mid = n / 2;
int[] l = new int[mid];
int[] r = new int[n - mid];
for (int i = 0; i < mid; i++) {
l[i] = a[i];
}
for (int i = mid; i < n; i++) {
r[i - mid] = a[i];
}
mergeSort(l, mid);
mergeSort(r, n - mid);
merge(a, l, r, mid, n - mid);
}
Also in Java:
- how to check the lines in a file java scanner
- java bubble sort short circuit
- import classes from another project java
- compile java to jar in mac
- string array in java methods
- fxmlloader getresource from another package
- java declare an int inside an if statement
- java sql question mark
- [ERROR] Error executing Maven. java.io.FileNotFoundException: The specified user settings file does not exist: /usr/lib/jvm/java-1.8.0-openjdk-amd64
- how to replace all of one character with nothing in java
- Matlab java.lang.IllegalArgumentException: Invalid range
- dataframe to dict without index
- find frequency of each word in a string in java
- java 8 retrieve all list from object into single list and ignore duplicates
- how to create a method java
- java 8 function supplier consumer
- bitwise operator in java
- processing string to int
- processing sound android
- Java.awt graphics tutorial
- java classes and methods simple logic with comments
- socket in java
- java create window
- for loop java