publicclassThirdWayQuickSort{ publicstaticvoidquickSort3Way(int[] a, int left, int right){ //递归终止条件,少于等于一个元素的数组已有序 if (left >= right) { return; } int i, j, k, pivot; //首元素作为中轴 pivot = a[left]; i = left; k = left + 1; j = right;
privatestaticvoidswap(int[] a, int i, int j){ int temp = a[i]; a[i] = a[j]; a[j] = temp; }
publicstaticvoidmain(String[] args){ int[] a = newint[100000000]; Random r = new Random(); for (int i = 0; i < a.length; i++) { a[i] = r.nextInt(100000); } System.out.println("ThirdWayQuickSort排序开始:"); long start = System.currentTimeMillis(); quickSort3Way(a,0,a.length-1); System.out.println("ThirdWayQuickSort耗时:"+(System.currentTimeMillis()-start)+"ms"); System.out.println("ThirdWayQuickSort排序完成!"); System.out.println("数组是否有序:"+isOrdered(a)); } }
publicstaticvoidmain(String[] args){ int[] a = newint[100000000]; Random r = new Random(); for (int i = 0; i < a.length; i++) { a[i] = r.nextInt(10000); } int[] b = a.clone(); int[] c = a.clone();
System.out.println("ThirdWayQuickSort排序开始:"); long start = System.currentTimeMillis(); quickSort3Way(a,0,a.length-1); System.out.println("ThirdWayQuickSort耗时:"+(System.currentTimeMillis()-start)+"ms"); System.out.println("ThirdWayQuickSort排序完成!"); System.out.println("数组是否有序:"+isOrdered(a));
System.out.println("DualPivotQuickSort排序开始:"); long start1 = System.currentTimeMillis(); DualPivotQuickSort.dualPivotQuickSort(b,0,b.length-1); System.out.println("DualPivotQuickSort耗时:"+(System.currentTimeMillis()-start1)+"ms"); System.out.println("DualPivotQuickSort排序完成!"); System.out.println("数组是否有序:"+isOrdered(b));
System.out.println("QuickSort排序开始:"); long start2 = System.currentTimeMillis(); QuickSort.quickSort(c,0,c.length-1,true); System.out.println("QuickSort耗时:"+(System.currentTimeMillis()-start2)+"ms"); System.out.println("QuickSort排序完成!"); System.out.println("数组是否有序:"+isOrdered(c)); }
多次测试结果大致如下:
我们可以看到,当数据集重复元素较多时,三路快排确实有着比较优的排序效率。
我们将数据集范围改为[0,100),效果更加明显。
1 2 3
for (int i = 0; i < a.length; i++) { a[i] = r.nextInt(100); }
我们增大数据集范围,改为[0,100000000),再来测试一下。
1 2 3
for (int i = 0; i < a.length; i++) { a[i] = r.nextInt(100000000); }