【发布时间】:2015-03-22 19:29:09
【问题描述】:
public class SortingArray
{
public static void main(String[] args)
{
int[] array1 = { 1, 2, 3, 4, 5};
bubbleSort(array1);
}
public static void bubbleSort(int[] array2)
{
// Display the array's contents.
System.out.println("Original order: ");
for (int element : array2)
System.out.print(element + " ");
int lastPos; // Position of last element to compare
int index; // Index of an element to compare
int temp; // Used to swap to elements
int count = 0;
int count2 = 1;
// The outer loop positions lastPos at the last element
// to compare during each pass through the array. Initially
// lastPos is the index of the last element in the array.
// During each iteration, it is decreased by one.
for (lastPos = array2.length - 1; lastPos >= 0; lastPos--)
{
// The inner loop steps through the array, comparing
// each element with its neighbor. All of the elements
// from index 0 thrugh lastPos are involved in the
// comparison. If two elements are out of order, they
// are swapped.
for (index = 0; index <= lastPos - 1; index++)
{
count2++;
// Compare an element with its neighbor.
if (array2[index] > array2[index + 1])
{
count++;
// Swap the two elements.
temp = array2[index];
array2[index] = array2[index + 1];
array2[index + 1] = temp;
}
}
}
count2++;
// Display the array's contents.
System.out.println("\nSorted order: ");
for (int element : array2)
System.out.print(element + " ");
System.out.print("\n Swaps:" + count);
System.out.print("\n Comparisons:" + count2);
}
}
我正在尝试在一个简单的冒泡排序程序中计算比较和交换,并且我知道我计算了正确数量的交换(在本例中为 0),但我不知道如何跟踪比较.我必须使用这个特定的代码,只需稍作修改。有人可以帮助我了解使用这个硬编码的 int 数组将进行多少次比较。现在,当我运行程序时,我得到 12,我认为这是正确的,但我并不是 100% 肯定。
【问题讨论】:
-
为什么
count2在所有循环之后都在末尾递增?它只能在(或即将发生的)比较(值)之后(或之前)递增,其中只有一个这样的表达式。识别它,然后确保前面的规则成立。 -
而
count2为什么要以1开头? -
当我在外观中尝试它时,我得到了 16 次比较,这对于这个数组中的数字来说似乎太高了。
-
@fabian 这是我的一个错误,抱歉,我一直在疯狂地试图弄清楚这一点,并且几乎尝试了所有方法。
-
现在我已经更改了 count2 = 0 并将 count2 放在外部 for 循环中,我得到了 15 个比较
标签: java