Java 泡泡排序排序很奇怪
我刚刚试着编写我的第一个排序算法A,它做了一些奇怪的事情。我不知道这是从哪里来的,但我认为它与数组长度有关。因为第一个数字总是等于数组长度。这里我把我写的简单代码放在这里,希望有人能帮助我调试它。提前非常感谢Java 泡泡排序排序很奇怪,java,algorithm,Java,Algorithm,我刚刚试着编写我的第一个排序算法A,它做了一些奇怪的事情。我不知道这是从哪里来的,但我认为它与数组长度有关。因为第一个数字总是等于数组长度。这里我把我写的简单代码放在这里,希望有人能帮助我调试它。提前非常感谢 public class BubbleSort { private static void sort(int[] pole) { for (int i = 0; i < pole.length; i++) { for (int j =
public class BubbleSort {
private static void sort(int[] pole) {
for (int i = 0; i < pole.length; i++) {
for (int j = 1; j < pole.length - i; j++) {
if (pole[j-1] > pole[j]) {
int tm = pole[j-1];
pole[j-1] = j;
pole[j] = tm;
}
}
}
}
public static void main(String[] args) {
int[] pole = { 65, 210, 41, 23, 3, 2, 4, 78 };
System.out.println("before: " + Arrays.toString(pole));
sort(pole);
System.out.println("after: " + Arrays.toString(pole));
}
}
公共类BubbleSort{
私有静态无效排序(int[]极){
对于(int i=0;i极点[j]){
int tm=极点[j-1];
极点[j-1]=j;
极点[j]=tm;
}
}
}
}
公共静态void main(字符串[]args){
int[]极={65210,41,23,3,2,4,78};
System.out.println(“before:+Arrays.toString(pole));
排序(极点);
System.out.println(“之后:“+Arrays.toString(pole));
}
}
如果检查,您的中有一个错误。您分配的是一个值的索引,而不是值本身-pole[j-1]=j代码>。因此,您应该将其更正为:
...
if(pole[j-1] > pole[j]) {
tm = pole[j-1];
//assign the value here
pole[j-1] = pole[j];
pole[j] = tm;
}
...