write a program to sort string using Bubble sort in java


In this core java programming tutorial we will write a program to sort string using Bubble sort in java.



Example 1 to sort string using Bubble sort in java>
Input = java
Output = aajv

Example 2 to sort string using Bubble sort in java>
Input = javaMadeSoEasy
Output = vysojedaaaaSME


Program/ example to string using Bubble sort in java >
/*
* write a program to sort string using Bubble sort in java
*/
public class BubbleSortOnString {
   String sortMethod(String s) {
          char ch[] = s.toCharArray();
          char chTemp;
          //bubble Sort - to perform reverse sorting
          for (int i = ch.length - 1; i > 1; i--) {
                 for (int j = 0; j < i; j++) {
                       if (ch[j] > ch[j + 1]) {
                              //Swap logic in below 3 lines
                              chTemp = ch[j];
                              ch[j] = ch[j + 1];
                              ch[j + 1] = chTemp;
                       }
                 }
          }
          return new String(ch);
   }
   public static void main(String[] args) {
          BubbleSortOnString o = new BubbleSortOnString();
          String stringToBeSorted= "java";
          //String stringToBeSorted= "javaMadeSoEasy"; //Test String
          System.out.println(o.sortMethod(stringToBeSorted));
   }
}
/*OUTPUT
aajv
*/


So in this core java programming tutorial we wrote a program to sort string using Bubble sort in java.


Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.



Related >













Level2 programs












No comments:

Post a Comment