You are here : Home / Core Java Tutorials / Interview Programs (beginner to advanced) in java / Level1 programs for (beginner)
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
>7) Write a Program to find out Fibonacci series using recursion - example in java - interview programs
>9) How to Remove duplicate elements from sorted array example in java - important interview programs
>11) Write a program to find out substring in given string example in java - important interview programs
Labels:
Core Java