Sort string array java

You are here to learn sort string array java.

Basically class String do not have method to sort string array. In java, to sort a string array we need to match each element of an array to the remaining elements. Then, if result is > 0 we have to swap them.

Also read – bubble sort in java

To do that let’s see a java program using nested for loop. In this nested for loop, inner loop starts with a + 1, where “a” is the variable of “outer for loop”.

import java.util.Arrays;

public class SortStringArray
{
   public static void main(String[] args) 
   { 
      String strPlaces[] = {"Great Barrier Reef", "Paris", "BoraBora", "Florence","Tokyo", "Cusco"};
      int size = strPlaces.length;
      for(int a = 0; a < size - 1; a++) 
      {
         for(int b = a + 1; b < strPlaces.length; b++) 
         {
            if(strPlaces[a].compareTo(strPlaces[b]) > 0) 
            {
               String temp = strPlaces[a];
               strPlaces[a] = strPlaces[b];
               strPlaces[b] = temp;
            }
         }
      }
      System.out.println(Arrays.toString(strPlaces));
   }
}

Output:

sort string array java


Using Arrays.sort() method

Arrays.sort() method sorts the specified array of objects into ascending order, according to the natural ordering of its elements.

Also read – quick sort in java

import java.util.Arrays;

public class JavaArraySort
{
public static void main(String[] args)
{
String strGiven[] = {"Great Barrier Reef", "Paris", "borabora", "Florence","tokyo", "Cusco"};
Arrays.sort(strGiven);
System.out.println("Output(case sensitive) : " + Arrays.toString(strGiven));
}
}

Output:

Output(case sensitive) : [Cusco, Florence, Great Barrier Reef, Paris, borabora, tokyo]


Also read – java sort both primitive and object array

Related Posts