我对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
答案 0 :(得分:0)
根据您的评论,您可以将计数变量设为静态,并将输出放在主方法中,如下所示:
public class IntBubbleSorter {
public static int count = 0;
public static int count2 = 0;
public static void bubbleSort(int[] array)
{
int lastPos;
int index;
int temp;
count = 0;
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;
}
}
}
}
}
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();
System.out.print("\n Swaps:" + IntBubbleSorter.count);
System.out.print("\n Comparisons:" + IntBubbleSorter.count2);
}
}
但我应该提到static
应谨慎使用。