如何统计为比例进行的#比较和掉期?

时间:2015-05-06 23:23:50

标签: java sorting heapsort

我试图找出用于比较和移动的增量器放在我的堆排序算法中的位置。比较是在评估两个整数时,不一定要移动。移动是指数组中的值与另一个值切换的时间。所以成功交换将是2次移动。

contains

请使用 public static void heapSort( int [] a ) { for( int i = a.length / 2; i >= 0; i-- ) /* buildHeap */ percDown( a, i, a.length ); for( int i = a.length - 1; i > 0; i-- ) { swapReferences( a, 0, i ); /* deleteMax */ percDown( a, 0, i ); } } /** * Internal method for heapsort. * @param i the index of an item in the heap. * @return the index of the left child. */ private static int leftChild( int i ) { return 2 * i + 1; } /** * Internal method for heapsort that is used in * deleteMax and buildHeap. * @param a an array of Comparable items. * @index i the position from which to percolate down. * @int n the logical size of the binary heap. */ private static void percDown( int[] a, int i, int n ) { int child; int tmp; for( tmp = a[i]; leftChild( i ) < n; i = child ) { child = leftChild( i ); if( child != n - 1 && a[child] < a[child + 1] ) child++; if( tmp < a[child]) a[ i ] = a[ child ]; else break; } a[ i ] = tmp; } /** * Method to swap to elements in an array. * @param a an array of objects. * @param index1 the index of the first object. * @param index2 the index of the second object. */ public static final void swapReferences( int [ ] a, int index1, int index2 ) { int tmp = a[ index1 ]; a[ index1 ] = a[ index2 ]; a[ index2 ] = tmp; } numMoves作为变量名称。

1 个答案:

答案 0 :(得分:0)

移动:在swapReferences方法中增加numMoves。

比较:在使用比较运算符的percDown中增加numCompares。