Open In App

Sort a String in Java (2 different ways)

Last Updated : 18 Mar, 2024
Suggest changes
Share
Like Article
Like
Report

The string class doesn't have any method that directly sorts a string, but we can sort a string by applying other methods one after another. The string is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created.

Creating a String

There are two ways to create a string in Java:

  • String literal
String s = “GeeksforGeeks”;
  • Using new keyword
String s = new String (“GeeksforGeeks”);

Note: As we know that String is immutable in java, hence in third step we have to create a new string.

Methods:

There exist two methods with which we can sort any string in java alphabetically

  1. Without using the sort() method
  2. By using the sort() method

Illustration:

Input string : "geeksforgeeks"
Output string : "eeeefggkkorss"

Now let us discuss methods and implement the same. 

Method 1: Without using the sort() method

Here we will be laying an approach to sort a string without using any predefined logic. So, it also does becomes an important approach from an interview perceptive view.

Procedure:

  1. Convert string to an array with the help of the toCharArray() method of the String class
  2. Now use nested loops to check for swapping elements of an array.
  3. Print these character array elements.

Example

Java
// Java program for Sorting a String without using any inbuilt sorting functions import java.io.*; class StringSort {  //The Merge Function, handling the core compare & copy logic  void merge(char arr[], int l, int m, int r)  {    int n1 = m - l + 1;  int n2 = r - m;  char L[] = new char[n1];  char R[] = new char[n2]; //Logic for backing up to temp arrays  for (int i = 0; i < n1; ++i)  L[i] = arr[l + i];  for (int j = 0; j < n2; ++j)  R[j] = arr[m + 1 + j];  int i = 0, j = 0;  int k = l;  //Logic to compare and copy. The core Merge Logic of the Merge sort.  while (i < n1 && j < n2) {  if (L[i] <= R[j]) {  arr[k] = L[i];  i++;  }  else {  arr[k] = R[j];  j++;  }  k++;  }  //Logic to copy remaining elements of L[]  while (i < n1) {  arr[k] = L[i];  i++;  k++;  }  //Logic to copy remaining elements of R[]  while (j < n2) {  arr[k] = R[j];  j++;  k++;  }  }  //The main Merge Sort function from where the sorting begins  void mergeSort(char arr[], int l, int r)  {  if (l < r) {  // Find the middle point  int m = l + (r - l) / 2;    // Sort first and second halves  mergeSort(arr, l, m);  mergeSort(arr, m + 1, r);    // Merge the sorted halves  merge(arr, l, m, r);  }  }  // A utility function to print char array of size n  static void printArray(char arr[])  {  int n = arr.length;  for (int i = 0; i < n; ++i)  System.out.print(arr[i] + " ");  System.out.println();  }  // Driver code  public static void main(String args[])  {  String inputString = "geeksforgeeks";  char arr[] = inputString.toCharArray();  System.out.println("Given array is");  printArray(arr);  StringSort ob = new StringSort();  ob.mergeSort(arr, 0, arr.length - 1);  System.out.println("\nSorted array is");  printArray(arr);  } } /* This code is contributed by Nikhil B */ 

Output:

eeeefggkkorss

Time Complexity: O(n * log n). (where 'n' is the size of input String.)


Method 2: By using the sort() method

2A By using the sort() method- natural sorting

Procedure:

  1. The main logic is to toCharArray() method of the String class over the input string to create a character array for the input string.
  2. Now use Arrays.sort(char c[]) method to sort character array.
  3. Use the String class constructor to create a sorted string from a char array.

Example 1

Java
// Java program to Sort a String Alphabetically // Using toCharArray() method // With using the sort() method // Importing Arrays class from java.util package import java.util.Arrays; // Main class public class GFG {  // Method 1  // To sort a string alphabetically  public static String sortString(String inputString)  {  // Converting input string to character array  char tempArray[] = inputString.toCharArray();  // Sorting temp array using  Arrays.sort(tempArray);  // Returning new sorted string  return new String(tempArray);  }  // Method 2  // Main driver method  public static void main(String[] args)  {  // Custom string as input  String inputString = "geeksforgeeks";  String outputString = sortString(inputString);  // Print and display commands  // Input string  System.out.println("Input String : " + inputString);  // Output string  System.out.println("Output String : "  + outputString);  } } 

Output
Input String : geeksforgeeks Output String : eeeefggkkorss

2B By using the sort() method- Custom sorting

Arrays.sort(char c[]) method sort characters based on their ASCII value, we can define our custom Comparator to sort a string. 

Illustration:

Input String : GeeksforGeeks
Output String : eeeefGGkkorss

Procedure: 

  1. Convert input string to Character array. There is no direct method to do it. We will use for loop to fill the array.
  2. Use Arrays.sort(T [ ], Comparator c) method to sort Character array. For this, we must have to implement compare() method based on our custom sorting behavior.
  3. Now we can use StringBuilder to convert the Character array to String.

Example 2

Java
// Java Program to Sort a Mixed String Containing // Uppercase and Lowercase Characters // Importing required classes import java.util.Arrays; import java.util.Comparator; // Main class class GFG {  // Method 1  // To sort a mixed string  public static String sortString(String inputString)  {  // Converting input string to Character array  Character tempArray[]  = new Character[inputString.length()];  for (int i = 0; i < inputString.length(); i++) {  tempArray[i] = inputString.charAt(i);  }  // Sort, ignoring case during sorting  Arrays.sort(tempArray, new Comparator<Character>() {    // Method 2  // To compare characters  @Override  public int compare(Character c1, Character c2)  {  // Ignoring case  return Character.compare(  Character.toLowerCase(c1),  Character.toLowerCase(c2));  }  });  // Using StringBuilder to convert Character array to  // String  StringBuilder sb  = new StringBuilder(tempArray.length);  for (Character c : tempArray)  sb.append(c.charValue());  return sb.toString();  }  // Method 3  // MAin driver method  public static void main(String[] args)  {  // Custom input string  String inputString = "GeeksforGeeks";  // Calling method 1 to sort input string  // and storing in a string  String outputString = sortString(inputString);  // Print and display the input and output strings  System.out.println("Input String : " + inputString);  System.out.println("Output String : "  + outputString);  } } 

Output
Input String : GeeksforGeeks Output String : eeeefGGkkorss

Note:

public int compare(Object o1, Object o2) {} 
  • have to return -ve if o1 has to come before o2
  • have to return +ve if o1 has to come after o2
  • have to return 0 if o1 is equal to o2



Next Article

Similar Reads

Practice Tags :