Java Bubble排序错误输出

时间:2013-09-18 16:01:06

标签: java sorting bubble-sort

我正在尝试实现一个基本的java冒泡排序,但我收到错误的输入..

代码是:

public class BubbleSort{
    public static void main(String args[]){

        int [] arr_sort=new int [] {5, 10, 50, 32, 52, 25};

        System.out.println("Bubble Sort");
        System.out.println("Before sorting: ");

        int x;
        for (x=0; x<6; x++){
        System.out.print(arr_sort[x] + " ");
        }
        System.out.println();
        System.out.println("After Sorting");

        int n = arr_sort.length;
        int temp = 0;

        for(int i=0; i<n; i++){
            for(int j=1; j<(n-1); j++){
                if(arr_sort[j-1] > arr_sort[j]){
                    temp = arr_sort[j-1];
                    arr_sort[j-1] = arr_sort[j];
                    arr_sort[j] = temp;
                }
            } System.out.print(arr_sort[i] + " ");
        }
    }
}

结果:

Bubble Sort
Before sorting: 
5 10 50 32 52 25 

After Sorting
5 10 32 50 52 25 

Process completed.

数组的不同整数:

Bubble Sort

Before sorting: 
2 10 1 15 62 71 

After Sorting
2 2 10 15 62 71 

Process completed.

我很丢失,我不知道该怎么做..请帮忙......

提前致谢。 顺便说一句,这是一个功课。

3 个答案:

答案 0 :(得分:1)

for(int i = 0; i < n; i++) {
    for(int j = i+1; j < n; j++) {
        if(arr_sort[j] < arr_sort[i]) {
            temp = arr_sort[i];
            arr_sort[i] = arr_sort[j];
            arr_sort[j] = temp;
        }
    } 
}

答案 1 :(得分:0)

        for(int i=0; i<n; i++){
            for(int j=1; j<n-i; j++){
                if(arr_sort[j-1] > arr_sort[j]){
                    temp = arr_sort[j-1];
                    arr_sort[j-1] = arr_sort[j];
                    arr_sort[j] = temp;
                }
            } 
            System.out.print(arr_sort[n-i-1] + " ");
        }

已修复一些索引问题。试试上面的代码。它虽然按降序输出数组。

答案 2 :(得分:0)

boolean flag = true;
while (flag){
  flag = false;
  for(int j = i+1; j < n; j++) {
        if(arr_sort[j] < arr_sort[i]) {
            temp = arr_sort[i];
            arr_sort[i] = arr_sort[j];
            arr_sort[j] = temp;
            flag= true;
        }
    } 
}

那是经典的泡泡排序......