Search code examples
javasortingmethodsstatic-methodsbubble-sort

Bubble sort in java , method (static or non staic)? ,(void or int[] )?,instance variable needed?


Can someone explain for me when do I use static /non-static , void or int[]x , and when do I use instance variables

because I can't seem to figure out which is when resulting in errors like this in the bubble sort code

public class PA2 {
//int []a ;
//int maxsize ;
//int temp;
public static int[] bubblesort(int [] a1) {
    int temp ;
    for(int i=0;i<a.length-1;i++) {
        for(int j=0 ; j<a.length-1-i;j++) {
        if(a[i]>a[i+1])
       temp = a[i];
        a[i]=a[i+1];
        a[i+1]=temp;
        }   
    }
}
public static void main(String[] args) {
    int [] a1 = {11,5,14,10,2};
     bubblesort(a1);
    //a.bubblesort();
   //a.selectionsort();
   // a.insertionsort();     }      }

Solution

  • static /non-static:

    static = something which is at the class level and shared by all the instances of that class. For example - site_hit_count would be an attribute you would like to maintain at the class level. No matter how many instances are created, all should see the latest and current value. Application level caches (eg catalog information for all the products available) are also good example for static.

    non-static = any class level attribute which will vary for each instance. For example - In a class called Person - name/age/address etc are instance level attributes but NOT static since each Person would have its own values to above attributes.

    I would suggest you go through this language basic tutorial (this will clear a lot of above questions) - https://docs.oracle.com/javase/tutorial/java/nutsandbolts/index.html