Bubble Sort ( String )

i know u already  know about buble sort...
but usually u only use buble sort for numeric problem..
now..
i will show u how to use bubble sort in String arrangement...


public class bubbleSort{
    public static void main(String []args){
        String []str={ "ba" , "bb" , "bc" , "ca" , "cb" , "cc" , "aa" , "ab" , "ac"  };
       
        for(int i=1;i<str.length;i++){
            for(int j=0;j<str.length-1;j++){
                if(str[ j+1 ].compareTo(str[ j ])<0){


                    String temp=str[ j ];
                    str[ j ]=str[ j+1 ];
                    str[ j+1 ]=temp;
                }
            }
        }
        for(int i=0;i<str.length;i++){
            System.out.println(str[i]);
        }
        System.exit(0);
    }
}

Sample Running :

  aa
  ab
  ac
  ba
  bb
  bc
  ca
  cb
  cc 


    P/S : Hope this can help u...and please give some comment...Thank You...

                                                                                                                                                                                Created By : Z-man, 2011

2 comments: