快速打印比较

时间:2017-10-15 00:24:13

标签: java quicksort

以下是来自快速排序分区方法的代码:

public static void quickSort(int[] array) 
{
doQuickSort(array, 0, random1.length - 1);

 }
 private static void doQuickSort(int[] array, int start, int end)
 {
int pivotPoint;

 if(start < end)
 {
   pivotPoint = partition(array, start, end);

    doQuickSort(array,start, pivotPoint - 1);

    doQuickSort(array, pivotPoint +1, end); 
    }


  }
 private static int partition(int[] array, int start, int end)
{
int pivotValue = array[start];
int endOfLeftList = start;
int mid = (start + end)/2;;
int compare = 0;
int swap = 0;

  for(int scan = start + 1; scan <= end; scan++)
  {
   compare++;
   if(array[scan] < pivotValue)
   { 
     swap++;
     endOfLeftList++;
      swap(array, endOfLeftList, scan);
   }
  }

    System.out.println("\nComparisons: " + compare); 
    System.out.println("Swaps: " + swap);

  swap(array, start, endOfLeftList);

  return endOfLeftList;

}

使用随机生成的数组,似乎无论我把print语句放在哪里,当我调用整个quicksort方法时,它会像这样连续打印:

 Array Before QuickSort:
 40 27 13 58 42 41 84 4 75 96 
 Comparisons: 1
 Swaps: 1

 Comparisons: 2
 Swaps: 2

 Comparisons: 3
 Swaps: 2

 Comparisons: 4
 Swaps: 2

 Comparisons: 5
 Swaps: 2

 Comparisons: 6
 Swaps: 2

 Comparisons: 7
 Swaps: 3

 Comparisons: 8
 Swaps: 3

 Comparisons: 9
 Swaps: 3

 Comparisons: 1
 Swaps: 0

 Comparisons: 2
 Swaps: 0

 Comparisons: 1
 Swaps: 1

 Comparisons: 1
 Swaps: 1

 Comparisons: 2
 Swaps: 1

 Comparisons: 3
 Swaps: 1

 Comparisons: 4
 Swaps: 1

 Comparisons: 5
 Swaps: 1

 Comparisons: 1
 Swaps: 1

 Comparisons: 2
 Swaps: 2

 Comparisons: 3
 Swaps: 2

 Comparisons: 1
 Swaps: 1

 Array After QuickSort:
 4 13 27 40 41 42 58 75 84 96 

我必须忽略一些事情,但我不确定。我试图让它只打印一次,说明有多少比较,有多少交换。如果需要,我将使用其他信息进行编辑。

2 个答案:

答案 0 :(得分:0)

这种情况正在发生,因为对于快速排序,您可能会在数组排序之前大量调用partition方法。因此,要仅获得总计数一次,并且在完成该过程后,您应该这样做:

将这些变量设为全局:

int compare = 0;
int swap = 0;

无论你的主要排序功能是什么,只需在调用后输入这些print语句:

System.out.println("\nComparisons: " + compare); 
System.out.println("Swaps: " + swap);

修改

因此,根据您编辑的问题,您应该在quickSort方法中使用这样的打印语句:

public static void quickSort(int[] array) 
{
    doQuickSort(array, 0, random1.length - 1);
    System.out.println("\nComparisons: " + compare); 
    System.out.println("Swaps: " + swap);
}

或在您拨打quickSort之后的任何地方:

quickSort(someIntArray);
System.out.println("\nComparisons: " + compare); 
System.out.println("Swaps: " + swap);

答案 1 :(得分:0)

每次打印比较的原因是因为每次需要分区时都使用此功能,快速排序很多次。

如果您只想显示结束,那么您应该创建一个单独的函数来打印比较次数

例如:

try
{
    git | Out-Null
   "Git is installed"
}
catch [System.Management.Automation.CommandNotFoundException]
{
    "No git"
}