我正在使用这个课程作为另一个课程的一部分,我想知道为什么第二个System.out.print
没有打印任何东西。我对其他算法做了同样的事情并且工作得很好。它仍然在方法内,所以我不确定为什么它不会打印
public class EnhancedBubbleSort
{
int temp = 0;
boolean sorted = false;
long counter1 = 0, counter2 = 0;
public void sort(int[] numbers)
{
System.out.print("Before Enhanced Bubble Sort: ");
for(int a: numbers)
System.out.print(a + ", ");
int lastSwap = numbers.length-1;
for(int i=1; i<numbers.length; i++)
{
boolean is_sorted = true;
int currentSwap = -1;
for(int j=0; j < lastSwap; j++)
{
counter1++;
if(numbers[j] > numbers[j+1])
{
counter2++;
temp = numbers[j];
numbers[j] = numbers[j+1];
numbers[j+1] = temp;
is_sorted = false;
currentSwap = j;
}
}
if(is_sorted)
return;
lastSwap = currentSwap;
}
System.out.print("\nAfter Enhanced Bubble Sort: ");
for(int a: numbers)
System.out.print(a + ", ");
}
}
答案 0 :(得分:1)
请修改下面的代码,它可以正常工作:
class EnhancedBubbleSort
{
int temp = 0;
boolean sorted = false;
long counter1 = 0, counter2 = 0;
public void sort(int[] numbers)
{
System.out.print("Before Enhanced Bubble Sort: ");
for(int a: numbers)
System.out.print(a + ", ");
int lastSwap = numbers.length-1;
for(int i=1; i<numbers.length; i++)
{
boolean is_sorted = true;
int currentSwap = -1;
for(int j=0; j < lastSwap; j++)
{
counter1++;
if(numbers[j] > numbers[j+1])
{
counter2++;
temp = numbers[j];
numbers[j] = numbers[j+1];
numbers[j+1] = temp;
is_sorted = false;
currentSwap = j;
}
}
if(is_sorted)
break; // Use break statement instead of return one
lastSwap = currentSwap;
}
System.out.print("\nAfter Enhanced Bubble Sort: ");
for(int a: numbers)
System.out.print(a + ", ");
}
}
输出:
jshell> new EnhancedBubbleSort().sort(data)
Before Enhanced Bubble Sort: 1, 2, 3, 4,
After Enhanced Bubble Sort: 1, 2, 3, 4,
答案 1 :(得分:0)
当您执行/**
* Parses the given string as an Instant, and returns null if not parseable
*/
public Instant parse(String s) {
try {
return Instant.parse(s);
}
catch (DateTimeParseException e) {
return null;
}
}
时,您将离开if(is_sorted) return;
,并且不会执行任何进一步的陈述。您想要做的是void sort()
,离开if(is_sorted) break;
循环。