Search code examples
javabubble-sort

Java BubbleSort


I am facing a problem where I need to sort a String array in alphabetical order. I am able to sort one array, but the problem starts when there are 2 more arrays, that correspond to the first array. Each value in each array should be in the same place, to make information not messed up. After sorting array1, it is in alphabetical order, but i don't have any idea how to make values from array2 and array3 change the positions the same like in array1 after sorting is finished.

My code so far is:

public  void sort() 
{

    boolean finish = false;

    while(finish == false){

        finish = true;

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

        {
            int num = 0;
            if(Country[i] != null && Country[i + 1] != null)
            {
                String name1=Country[i]; String name2=Country[i+1];
                num=name1.compareTo(name2);
            }
            else if(Country[i] == null && Country[i + 1] == null){
                num = 0;
            }
            else if(Country[i] == null){
                num = 1;
            }
            else {
                num = -1;
            }
            if(num>0)
            {
                String temp=Country[i];

                Country[i]=Country[i+1];
                Country[i+1]=temp;
                finish=false;
            }
        }
    }

Solution

  • By far the most recommended way is to re-design your program, and arrange all the related items in a single class. This is what objects are for, after all. Then you can make the object Comparable, give it a compareTo method, and sort it.

    But if you are really unable to do that, what you should do is, whenever you exchange any two items in your sort array, make sure you exchange the corresponding items in the other arrays.

    So, if you have arrays country, capital and headOfState, you will have to write something like:

      String temp=country[i];
    
      country[i]=country[i+1];
      country[i+1]=temp;
    
      temp=capital[i];
      capital[i]=capital[i+1];
      capital[i+1]=temp;
    
      temp=headOfState[i];
      headOfState[i]=headOfState[i+1];
      headOfState[i+1]=temp;
    

    This way, whenever you move anything in your main array, you'll also be moving the respective item in the other arrays, so they will stay together.

    But again, it's much more preferred if you re-designed your program.

    Also note the Java language conventions - variable names should not start with a capital letter, only type names should.