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 in reverse order using Insertion sort in java.
Example 1 to sort string in reverse order using Insertion sort in java>
Input = java
Output = vjaa
Example 2 to sort string in reverse order using Insertion sort in java>
Input = javaMadeSoEasy
Output = vysojedaaaaSME
Program/ example to sort string in reverse order using Insertion sort in java>
/*
* write a program to sort string in reverse order using Insertion sort in java
*/
public class InsertionSortReverseOnString {
public static void main(String[] args) {
String stringToBeSorted = "java";
// String stringToBeSorted= "javaMadeSoEasy"; //Test String
System.out.println(sort(stringToBeSorted));
}
// Insertion Sort - to perform reverse sorting
static String sort(String s) {
int tempPos;
char ch[] = s.toCharArray();
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
vjaa
*/
|
So in this core java programming tutorial we wrote a program to sort string in reverse order 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 >
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