Java Program to Sort a List of String in Alphabetically

Java program to sort a list of string in alphabetically.
class string
{
 public static void main(String args[])
 {
  String city[]={"Delhi","Bangalore","Mumbai","Hyderabad","Agra"};
  int l=city.length,i,j;
  System.out.println("The name of cities are:");
  for(i=0;i<l;i++)
  System.out.println(city[i]);
  for(i=0;i<l;i++)
  {
   for(j=i+1;j<l;j++)
   {
    if(city [i].compareTo(city[j])>0)
    {
     String t=city[i];
     city [i]=city [j];
     city[j]=t;
    }
   }
  }
  System.out.println("The name of cities in sorted form are:");
  for(i=0;i<l;i++)
  System.out.println(city [i]);
 }
}

Output:

The name of cities are:
Delhi
Bangalore
Mumbai
Hyderabad
Agra
The name of cities in sorted form are:
Agra
Bangalore
Delhi
Hyderabad
Mumbai

Post a Comment

0 Comments