Search code examples
javasortingbubble-sort

BubbleSort using integer Array


I have been trying to implement Bubble Sort using simple integer array in java. However there seems to be some problem. Now i know that using ArrayList would be the best option and I would do that too. But why isnt it getting sorted with simple integer array.Here is the code

package sort;

public class BubbleSort {

    int array[]={1,5,3,32,54,6,87,5,1};
    int temp=0;
public void enter(){
    for(int i=0;i<array.length;i++){
        for(int j=0;j<(array.length-i);j++){
            if(array[j]>=array[j+1]){


                temp=array[j];
                array[j]=array[j+1];
                array[j+1]=temp;
                }

        }
    }
}
public void show(){

    for(int i:array){
    System.out.println(i);
    }
}
public static void main(String str[]){

    new BubbleSort().Enter();
    new BubbleSort().Show();
}
}

Its producing the same array as entered. Nothing is getting changed. The difference between a simple array and an ArrayList or Vector ,is just that they offer dynamic time expansion of array size.Is there anything more to it? I mean does simple array creates a different instance every time it is manipulated, just like Strings? It does seem to do so here.


Solution

  • The problem is that you're not assigning a name to the instantiation of your BubbleSort class.

    new BubbleSort().Enter();
    new BubbleSort().Show();
    

    Your code creates a new BubbleSort class, and then sorts it. And then it creates another new (and completely separate) BubbleSort class, and displays that one instead - and it hasn't been sorted.

    You want to give a name to your variable, so you can sort it and then display it, like this:

    BubbleSort myBubbleSort = new BubbleSort();
    myBubbleSort.Enter();
    myBubbleSort.Show();
    

    As a side note (and as pointed out in SiB's answer), you may also want to check out the Java Naming Conventions. Following these conventions makes your code more legible to other Java programmers, and includes things like using lowerCamelCase for method names, and UpperCamelCase for class names.