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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| public class QuickSort {
public static void quickSort(int[] arr, int startIndex, int endIndex) { if (startIndex >= endIndex) { return; } int pivotIndex = partition(arr, startIndex, endIndex); quickSort(arr, startIndex, pivotIndex - 1); quickSort(arr, pivotIndex + 1, endIndex); }
public static void quickSortWithStack(int[] arr, int startIndex, int endIndex) { Stack<Map<String, Integer>> quickSortStack = new Stack<> (); Map rootParam = new HashMap(); rootParam.put("startIndex", startIndex); rootParam.put("endIndex", endIndex); quickSortStack.push(rootParam);
while (!quickSortStack.isEmpty()) { Map<String, Integer> param = quickSortStack.pop(); int pivotIndex = partition(arr, param.get("startIndex"), param.get("endIndex")); if (param.get("startIndex") < pivotIndex - 1) { Map<String, Integer> leftParam = new HashMap<> (); leftParam.put("startIndex", param.get("startIndex")); leftParam.put("endIndex", pivotIndex - 1); quickSortStack.push(leftParam); } if (pivotIndex + 1 < param.get("endIndex")) { Map<String, Integer> rightParam = new HashMap<> (); rightParam.put("startIndex", pivotIndex + 1); rightParam.put("endIndex", param.get("endIndex")); quickSortStack.push(rightParam); } } }
private static int partition(int[] arr, int startIndex, int endIndex) { int pivot = arr[startIndex]; int left = startIndex; int right = endIndex;
while (left != right) { while (left < right && arr[right] > pivot) { right--; } while (left < right && arr[left] <= pivot) { left++; } if (left < right) { int p = arr[left]; arr[left] = arr[right]; arr[right] = p; } }
arr[startIndex] = arr[left]; arr[left] = pivot;
return left; }
private static int partitionV2(int[] arr, int startIndex, int endIndex) { int pivot = arr[startIndex]; int mark = startIndex;
for (int i = startIndex + 1; i <= endIndex; i++) { if (arr[i] < pivot) { mark++; int p = arr[mark]; arr[mark] = arr[i]; arr[i] = p; } }
arr[startIndex] = arr[mark]; arr[mark] = pivot; return mark; }
public static void main(String[] args) { int[] arr = new int[] {4, 4, 6, 5, 3, 2, 8, 1}; quickSort(arr, 0, arr.length - 1); System.out.println(Arrays.toString(arr)); } }
|