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 Insertion sort in java.
Example 1 to sort string using Insertion sort in java>
Input = java
Output = aajv
Example 2 to sort string using Insertion sort in java>
Input = javaMadeSoEasy
Output = vysojedaaaaSME
Program/ example to sort string using Insertion sort in java >
/*
* write a program to sort string using Insertion sort in java
*/
public class InsertionSortOnString {
public static void main(String[] args) {
String stringToBeSorted= "java";
//String stringToBeSorted= "javaMadeSoEasy"; //Test String
System.out.println(sort(stringToBeSorted));
}
static String sort(String s) {
int tempPos;
char ch[] = s.toCharArray();
// Insertion Sort - to perform sorting
for (int i = ch.length - 1; i > 0; i--) {
tempPos = i;
for (int j = i; j > 0; j--) {
if (ch[j - 1] > ch[tempPos]) {
tempPos = j - 1;
}
}
swap(ch, tempPos, i);
}
return new String(ch);
}
static void swap(char ch[],int tempPos,int i){
char temp=ch[tempPos];
ch[tempPos]=ch[i];
ch[i]=temp;
}
}
/*OUTPUT
aajv
*/
|
So in this core java programming tutorial we wrote a program to sort string using Insertion 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 >
Level3 programs
Labels:
Core Java