write a program to sort string in reverse order using Insertion sort in java


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












Labels: Core Java
eEdit
Must read for you :