Last active
October 23, 2025 09:30
-
-
Save maycuatroi1/890403fde981b421efc4fbad87e9b253 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=uf_DyA_Ku7A | |
| public class QuickSort { | |
| // Helper method để hoán đổi hai phần tử | |
| private static void swap(int[] arr, int i, int j) { | |
| int temp = arr[i]; | |
| arr[i] = arr[j]; | |
| arr[j] = temp; | |
| } | |
| // Hàm tìm vị trí Pivot và sắp xếp mảng | |
| public static int partition(int[] arr, int low, int high) { | |
| int pivot = arr[high]; // Chọn phần tử cuối làm Pivot | |
| int i = (low - 1); // index của phần tử nhỏ hơn Pivot | |
| for (int j = low; j < high; j++) { | |
| // Nếu phần tử hiện tại nhỏ hơn hoặc bằng Pivot | |
| if (arr[j] <= pivot) { | |
| i++; | |
| swap(arr, i, j); | |
| } | |
| } | |
| // Hoán đổi arr[i + 1] và arr[high] (hoặc Pivot) | |
| swap(arr, i + 1, high); | |
| return i + 1; | |
| } | |
| public static void quickSort(int[] arr, int low, int high) { | |
| if (low < high) { | |
| // Tìm chỉ số Pivot để chia mảng | |
| int pi = partition(arr, low, high); | |
| // Sắp xếp đệ quy các phần tử trước và sau Pivot | |
| quickSort(arr, low, pi - 1); | |
| quickSort(arr, pi + 1, high); | |
| } | |
| } | |
| public static void main(String[] args) { | |
| int[] arr = {64, 25, 12, 22, 11}; | |
| quickSort(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