以下是Java中的快速排序的简单实现代码:
public class QuickSort { public static void quickSort(int[] arr, int left, int right) { if (left < right) { int pivot = partition(arr, left, right); quickSort(arr, left, pivot - 1); quickSort(arr, pivot + 1, right); } } private static int partition(int[] arr, int left, int right) { int pivot = arr[right]; int i = left - 1; for (int j = left; j < right; j++) { if (arr[j] < pivot) { i++; swap(arr, i, j); } } swap(arr, i + 1, right); return i + 1; } private static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } }
使用示例:
int[] arr = {5, 2, 9, 1, 5, 6}; QuickSort.quickSort(arr, 0, arr.length - 1); System.out.println(Arrays.toString(arr)); // 输出 [1, 2, 5, 5, 6, 9]
评论