1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
public class QuickSort { public static void quickSort(int[] arr, int low, int high) { if (low < high) { int pivotIndex = partition(arr, low, high); quickSort(arr, low, pivotIndex - 1); quickSort(arr, pivotIndex + 1, high); } }
private static int partition(int[] arr, int low, int high) { int pivot = arr[(low + high) / 2]; int i = low, j = high; while (i <= j) { while (arr[i] < pivot) i++; while (arr[j] > pivot) j--; if (i <= j) { swap(arr, i, j); i++; j--; } } return i; }
private static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }
public static void main(String[] args) { int[] arr = {5, 3, 8, 4, 2, 7, 1, 6}; quickSort(arr, 0, arr.length - 1); System.out.println(Arrays.toString(arr)); } }
|