Java program to Sort Array of strings / Elements.

For Soring the Array of Strings, Simply we can use the sort method of Arrays class. Or we can write algorithm to sort the array of strings. In this post, I have written in  both ways.

A) In the first example, sort method of Arrays class has been used for sorting .

B) In the IInd example, two loops are used to sort the content of the array.

Steps :

i) Compare the first element with all other (1+) elements.

ii) If the first element is greater than any other element, then we have to swap both element. Now the first element is in the order.

iii)  Now Compare the second element with all other (2+) elements and repeat above steps .. this process is continued upto the element n-1.

Example 1 :


package com.javaonline;

import java.util.Arrays;

public class StringSort {
public static void main(String[] args) {
String[] arrayList = new String[] { "Pine Apple", "Banana", "Apple", "Pears", "Orange" };

System.out.println("Before sorting the array: " + Arrays.asList(arrayList));

Arrays.sort(arrayList); // sort method used to sort the array contents .

System.out.println("After sorting the array: " + Arrays.asList(arrayList));
}
} 

Running the above program

string sort1

Example 2 :


package com.javaonline;
import java.util.Arrays;

public class StringSort1 {
public static void main(String[] args) {
String[] arrayList = new String[] { "New York", "Delhi", "Chennai", "Bangalore", "Bombay"};
String temp="";

System.out.println("Before sorting the Array: " + Arrays.asList(arrayList));

// Logic for sorting

for (int i=0;i<=arrayList.length-1;i++)
{
for (int j=i+1;j<=arrayList.length-1;j++)
{
if (arrayList[i].compareTo(arrayList[j])>0 )
{
temp=arrayList[i];
arrayList[i]=arrayList[j]; // Inerchange of element
arrayList[j]=temp;
}

}
}

System.out.println("After sorting the Array: ");
for (int i=0;i<arrayList.length;i++)
{
System.out.print(arrayList[i] +" ");
}
}
}

Running the Program

string sort

You may also like

Leave a Reply