Write a Java Program for sorting a given list of names in ascending order.


Program Code in JAVA:
import java.io.*;
class SortingStr
{
public static void main(String[] args) throws Exception
{
int n,i,j;
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Ente the number of Strings :");
n=Integer.parseInt(dis.readLine());
String str[]=new String[n];
for(i=0;i<n;i++)
{
System.out.println("Enter string "+(i+1)+" :");
str[i]=dis.readLine();
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if((str[i].compareTo(str[j]))>0)
{
String tmp=str[i];
str[i]=str[j];
str[j]=tmp;
}
}
}
System.out.println("The String after Sorting : ");
for(i=0;i<n;i++)
System.out.println(str[i]);
}
}


Program Output:
c:\java>javac SortingStr.java
c:\java>java SortingStr
Ente the number of Strings :
5
Enter string 1 : rama
Enter string 2 : krishna
Enter string 3 : raju
Enter string 4 : abc
Enter string 5 : sai
The String after Sorting :
abc
krishna
raju
rama
sai
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: