【发布时间】:2016-11-25 22:38:39
【问题描述】:
我对 Java 还很陌生。我正在一个 int 数组上创建排序算法,这样每个方法都会计算它们进行的交换和比较的数量。我在显示原始订单、排序订单、掉期和比较时遇到问题。不知道我必须做些什么来修复它。任何帮助将不胜感激。
public class IntBubbleSorter {
public static void bubbleSort(int[] array)
{
int lastPos;
int index;
int temp;
int count = 0;
int count2 = 0;
for (lastPos = array.length - 1; lastPos >= 0; lastPos--)
{
for (index = 0; index <= lastPos - 1; index++)
{
count2++;
if (array[index] > array[index + 1])
{
count++;
temp = array[index];
array[index] = array[index + 1];
array[index + 1] = temp;
}
}
}
System.out.print("\n Swaps:" + count);
System.out.print("\n Comparisons:" + count2);
}
}
public class SortingTest {
public static void main(String[] args)
{
int[] values = { 1,53,86,21,49,32,90,65,33,11,34,68,54,32,78,80,35,22,96,59,265,44324,123,3123,25435};
System.out.println("Original Order: ");
for (int element : values)
System.out.print(element + " ");
IntBubbleSorter.bubbleSort(values);
System.out.println("\nSorted order: ");
for (int element : values)
System.out.print(element + " ");
System.out.println();
}
}
//这是输出的内容
Original Order:
1 53 86 21 49 32 90 65 33 11 34 68 54 32 78 80 35 22 96 59 265 44324 123 3123 25435
Swaps:80
Comparisons:300
Sorted order:
1 11 21 22 32 32 33 34 35 49 53 54 59 65 68 78 80 86 90 96 123 265 3123 25435 44324
【问题讨论】:
-
你为什么认为这不正确?
-
主要方法是获取原始订单,然后转到冒泡排序器并获取交换和比较,然后返回主要方法进行排序,这不是我想要的顺序,而是任何东西我试试不行。我将创建更多使用相同主要方法的排序方法,我认为它会变得非常混乱和混乱。我应该有某种“获取”方法来获取交换和比较吗?
-
这似乎很合理。您可能会考虑创建某种抽象基类来实现比较和交换功能,然后您的各种排序实现可以继承通用功能。我相信Sedgewick 采用了这种方法。
标签: java sorting bubble-sort