为什么这个bubbleSort方法不起作用?为什么需要另一个for循环?

时间:2019-04-02 06:03:32

标签: java arrays sorting

我在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]

2 个答案:

答案 0 :(得分:0)

您只通过了一次。您将不得不再做几次:

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;
            }
        }
    }
}

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

答案 1 :(得分:0)

再次阅读气泡排序。

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;
             }
         }
     }
 }