Last active
October 23, 2025 09:29
-
-
Save maycuatroi1/b649abf92266cfc4725bc6196d44f3ff to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://www.youtube.com/watch?v=WYrMGRJ9qFE | |
| public class MergeSort { | |
| // Gộp 2 mảng con đã được sắp xếp | |
| public static void merge(int[] arr, int left, int mid, int right) { | |
| // tính kích thước 2 mảng con | |
| int n1 = mid - left + 1; // Array trái | |
| int n2 = right - mid; // Array phải | |
| // Tạo mảng tạm | |
| int[] L = new int[n1]; | |
| int[] R = new int[n2]; | |
| // Sao chép dữ liệu vào mảng tạm | |
| System.arraycopy(arr, left, L, 0, n1); | |
| System.arraycopy(arr, mid + 1, R, 0, n2); | |
| // Gộp mảng tạm trở lại mảng chính | |
| int i = 0, j = 0; | |
| int k = left; | |
| while (i < n1 && j < n2) { | |
| if (L[i] <= R[j]) { | |
| arr[k++] = L[i++]; | |
| } else { | |
| arr[k++] = R[j++]; | |
| } | |
| } | |
| // Sao chép phần tử còn lại (chỉ một trong hai mảng còn phần tử) | |
| copyRemaining(L, i, n1, arr, k); | |
| copyRemaining(R, j, n2, arr, k + (n1 - i)); | |
| } | |
| // Helper method để sao chép phần tử còn lại | |
| private static void copyRemaining(int[] src, int srcIndex, int srcLength, int[] dest, int destIndex) { | |
| while (srcIndex < srcLength) { | |
| dest[destIndex++] = src[srcIndex++]; | |
| } | |
| } | |
| public static void mergeSort(int[] arr, int left, int right) { | |
| if (left < right) { | |
| int mid = (left + right) / 2; | |
| // Sắp xếp mảng con bên trái | |
| mergeSort(arr, left, mid); | |
| // Sắp xếp mảng con bên phải | |
| mergeSort(arr, mid + 1, right); | |
| // Gộp hai mảng con đã sắp xếp | |
| merge(arr, left, mid, right); | |
| } | |
| } | |
| public static void main(String[] args) { | |
| int[] arr = {64, 25, 12, 22, 11}; | |
| mergeSort(arr, 0, arr.length - 1); | |
| System.out.println("Sorted array:"); | |
| for (int num : arr) { | |
| System.out.print(num + " "); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment