Java Bubble Sort wrong output

不打扰是莪最后的温柔 提交于 2020-01-04 18:17:46

问题


I'm trying to implement a basic java bubble sort but I'm getting a wrong input..

Code is:

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] + " ");
        }
    }
}

Result:

Bubble Sort
Before sorting: 
5 10 50 32 52 25 

After Sorting
5 10 32 50 52 25 

Process completed.

A different integer for array:

Bubble Sort

Before sorting: 
2 10 1 15 62 71 

After Sorting
2 2 10 15 62 71 

Process completed.

I'm seriously lost and I don't know what to do.. please help..

Thanks in advance. This is a homework by the way.


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



回答2:


        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] + " ");
        }

A few index issues have been fixed. Try the code above. It outputs the array in descending order though.




回答3:


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

thats the classic bubble sort...



来源:https://stackoverflow.com/questions/18877036/java-bubble-sort-wrong-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!