How can we sort a string without using predefined methods in Java?

JavaObject Oriented ProgrammingProgramming

A String is an object that represents an immutable sequence of characters and cannot be changed once created. The java.lang.String class can be used to create a string object.

In the below program, we can sort the characters of a string without using any predefined methods of String class in Java.

Example

public class SortStringWithoutPredefinedMethodsTest {
   public static void main(String[] args) {
      String str = "jdkoepacmbtr";
      System.out.println("Before Sorting:" + str);
      int j = 0;
      char temp = 0;
      char[] chars = str.toCharArray();
      for(int i=0; i < chars.length; i++) {
         for(j=0; j < chars.length; j++) {
            if(chars[j] > chars[i]) {
               temp = chars[i];
               chars[i] = chars[j];
               chars[j] = temp;
            }
         }
      }
      System.out.println("After Sorting:");
      for(int k=0; k < chars.length; k++) {
         System.out.println(chars[k]);
      }
   }
}

Output

Before Sorting: jdkoepacmbtr
After Sorting:
a
b
c
d
e
j
k
m
o
p
r
t
raja
Published on 19-Aug-2019 17:08:14
Advertisements