From afbd3f7088f587462a2c1c9a27ee65c336ced1aa Mon Sep 17 00:00:00 2001 From: huangbotao <36856212+huangbotao@users.noreply.github.com> Date: Mon, 16 May 2022 10:53:26 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E5=BF=AB=E6=8E=92=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. 重复代码抽取为 swap 方法 2. 添加 随机获取 pivot 的机制 --- java/12_sorts/QuickSort.java | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/java/12_sorts/QuickSort.java b/java/12_sorts/QuickSort.java index 08136570..25365d87 100644 --- a/java/12_sorts/QuickSort.java +++ b/java/12_sorts/QuickSort.java @@ -1,5 +1,7 @@ package sorts; +import java.util.concurrent.ThreadLocalRandom; + /** * Created by wangzheng on 2018/10/16. */ @@ -20,25 +22,27 @@ private static void quickSortInternally(int[] a, int p, int r) { } private static int partition(int[] a, int p, int r) { + int pos = ThreadLocalRandom.current().nextInt(l, r + 1); + swap(a, pos, r); int pivot = a[r]; int i = p; for(int j = p; j < r; ++j) { if (a[j] < pivot) { - if (i == j) { - ++i; - } else { - int tmp = a[i]; - a[i++] = a[j]; - a[j] = tmp; + if (i != j) { + swap(a,i,j); } + ++i; } } - int tmp = a[i]; - a[i] = a[r]; - a[r] = tmp; + swap(a,i,r); System.out.println("i=" + i); return i; } + private static void swap(int[] a, int i, int j) { + int temp = a[i]; + a[i] = a[j]; + a[j] = temp; + } }