Created
October 23, 2025 07:18
-
-
Save maycuatroi1/48cfcfd4407f0f44b2f6bc119a4ac965 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
| 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 | |
| for (int i = 0; i < n1; i++) { | |
| L[i] = arr[left + i]; | |
| } | |
| for (int j = 0; j < n2; j++) { | |
| R[j] = arr[mid + 1 + j]; | |
| } | |
| // 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]; | |
| i++; | |
| } else { | |
| arr[k] = R[j]; | |
| j++; | |
| } | |
| k++; | |
| } | |
| // Sao chép phần tử còn lại của L[] nếu có | |
| while (i < n1) { | |
| arr[k] = L[i]; | |
| i++; | |
| k++; | |
| } | |
| // Sao chép phần tử còn lại của R[] nếu có | |
| while (j < n2) { | |
| arr[k] = R[j]; | |
| j++; | |
| k++; | |
| } | |
| } | |
| public static int[] 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); | |
| } | |
| return arr; | |
| } | |
| public static void main(String[] args) { | |
| int[] arr = {64, 25, 12, 22, 11}; | |
| arr = 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