Skip to content

Instantly share code, notes, and snippets.

@Efreitor2001
Last active September 8, 2022 23:46
Show Gist options
  • Save Efreitor2001/62628dbf0e8ccf16b77d6c8365ac3823 to your computer and use it in GitHub Desktop.
Save Efreitor2001/62628dbf0e8ccf16b77d6c8365ac3823 to your computer and use it in GitHub Desktop.
[Java] Сортировка слиянием
public class Program {
public static void main(String[] args) {
int[] l = {5, 2, 3, 1, 4};
int[] res = sortArray(l);
for (int i : res) {
System.out.print(i + " ");
}
}
public static int[] sortArray(int[] array) {
if (array == null) {
return null;
}
if (array.length < 2) {
return array;
}
int[] arrayB = new int[array.length / 2];
System.arraycopy(array, 0, arrayB, 0, array.length / 2);
int[] arrayC = new int[array.length - arrayB.length];
System.arraycopy(array, arrayB.length, arrayC, 0, array.length - arrayB.length);
sortArray(arrayB);
sortArray(arrayC);
mergeArray(array, arrayB, arrayC);
return array;
}
private static void mergeArray(int[] array, int[] arrayB, int[] arrayC) {
int positionB = 0;
int positionC = 0;
for (int c = 0; c < array.length; c++) {
if (positionB == arrayB.length) {
array[c] = arrayC[positionC];
positionC++;
} else if (positionC == arrayC.length) {
array[c] = arrayB[positionB];
positionB++;
} else if (arrayB[positionB] < arrayC[positionC]) {
array[c] = arrayB[positionB];
positionB++;
} else {
array[c] = arrayC[positionC];
positionC++;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment