Skip to content

Instantly share code, notes, and snippets.

@maycuatroi1
Last active October 23, 2025 09:30
Show Gist options
  • Select an option

  • Save maycuatroi1/890403fde981b421efc4fbad87e9b253 to your computer and use it in GitHub Desktop.

Select an option

Save maycuatroi1/890403fde981b421efc4fbad87e9b253 to your computer and use it in GitHub Desktop.
// 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