bnrfly bnrfly - 7 months ago 17
Java Question

Java Bubble sorting not working

I just want to write a program that sorts 3 integers. The integers are entered from the input dialog. My code is really simple. I just need to get some data and put them in array called

num
. and then I create a method to sort the data by using bubble-sort logic. that method called
sort
. I have added command to display the sorted result with
System.out.println("Sorted Result : "+Arrays.toString(num))
but that's not working.
The output just let me input data and then nothing happen.

Can anyone please tell me something I miss or what I did wrong?
Thank you.

package numThree;

import java.util.Scanner;
import java.util.Arrays;

public class sort {


public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
int[] num = new int[3];


//INPUT DATA
System.out.println("Enter integers : ");

for(int i=0;i<=num.length;i++){

num[i]=sc.nextInt();

}

sort(num);

}

//SORTING
public static void sort (int[] num){

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

for(int j=0;j<=num.length-i;j++){

if(num[j-1]>num[j]){
int temp = num[j];
num[j] = num[j-1];
num[j-1] = temp;
}

}


System.out.println("Sorted Result : "+Arrays.toString(num));

}


}

}

Answer

I believe you need a boolean flag to implement a bubble sort as you cannot know in advance how many times the loop will perform the swapping of consecutive elements.

Try this:

package numThree;

import java.util.Scanner;
import java.util.Arrays;

public class sort {


    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int[] num = new int[3];


        //INPUT DATA
        System.out.println("Enter integers : ");

        for(int i=0;i<=num.length;i++){

            num[i]=sc.nextInt();

        }

        sort(num);

    }

    //SORTING
    public static void sort (int[] num){
       boolean swapped = true;
       while(swapped){ 
           swapped = false;
           for(int i=0;i<num.length-1;i++){

                if(num[i]>num[i+1]){
                    int temp = num[i];
                    num[i] = num[i+1];
                    num[i+1] = temp;
                    swapped = true;
                }
           }
       }
       System.out.println("Sorted Result : "+Arrays.toString(num));
    }
}

Note it can still be slightly improved: each time around the loop the largest number will end up as far as it can get towards the end of of the array: there's no need to check or swap till the end each time. By using a variable as the upper limit of the index "i" and decreasing its value after the for loop you can reduce the total number of iterations.

int end = num.length-1;
while(swapped){ 
   swapped = false;
   for(int i=0;i<end;i++){

        if(num[i]>num[i+1]){
            int temp = num[i];
            num[i] = num[i+1];
            num[i+1] = temp;
            swapped = true;
        }
    }
    end--;
 }