为什么这个气泡排序方法不起作用?为什么它需要另一个 for 循环?



我在java中使用bubbleSort()时遇到了问题。什么不对数组进行排序

import java.util.*;
public class Example {
public static void bubbleSort(int[] x){
for(int i=0; i<x.length-1; i++){
if(x[i]>x[i+1]){
int t=x[i];
x[i]=x[i+1];
x[i+1]=t;
}
}
}
public static void main(String[] args) {
int[] xr={99,78,67,12,65,54,43,23,67,11};
System.out.println(Arrays.toString(xr)); //99,78,67
bubbleSort(xr);
System.out.println(Arrays.toString(xr)); //11, 12, 23, 43, 
}
}

这是给定代码的输出:

[99, 78, 67, 12, 65, 54, 43, 23, 67, 11] [78, 67, 12, 65, 54, 43, 23, 67, 11, 99]

你只通过一次。您将不得不再执行此操作几次:

public static void bubbleSort(int[] x){
for(int i=x.length - 1; i>0; i--){
for(int j=0; j<i; j++){
if(x[j]>x[j+1]){
int t=x[j];
x[j]=x[j+1];
x[j+1]=t;
}
}
}
}

它只检查相邻的值,所以当最小值是最后一个值时,在一次运行后,它将在倒数第二个位置(只有一次检查和位置交换)。因此,您需要在数组中有元素时多次执行此操作,但并不总是针对整个集合(第一次运行后,最大元素将位于最后一个位置,依此类推)。

再次读取气泡排序。

https://www.tutorialspoint.com/data_structures_algorithms/bubble_sort_algorithm.htm

for(int i=0; i<x.length-1; i++)

您的循环将只遍历数组一次。

int t=x[j];
x[j]=x[j+1];
x[j+1]=t;
}```
Within the loop, you are just swapping sibilling two elements as lower first if first one higher than the next one.
This will just bring the highest value to end of the array. Then what about the next highest value?. To sort completely, you need to do this swapping array element count number of times. O(n2)
https://en.wikipedia.org/wiki/Bubble_sort
so it should be like,
public static void bubbleSort(int[] x){
for(int j=0; j<x.length-1; j++){
for(int i=0; i<x.length-1; i++){
if(x[i]>x[i+1]){
int t=x[i];
x[i]=x[i+1];
x[i+1]=t;
}
}
}
}

最新更新