Problem Statement:
To sort an array of strings.
Algorithm
1) Start
2) Input the number of strings.
3) Read the string one by one using for loop.
4) Compare the elements within the string.
5) Repeat until i
8) t=str[j].
9) str[j]=str[j+1].
10) str[j+1]=t.
11) Print the sorted strings.
12) Stop.
Program
import java.io.*; class Str { public static void main(String arg[]) { DataInputStream in = new DataInputStream(System.in); String s[]=null,st=null; int i,j,n; try { System.out.println("\nEnter number of strings : "); n=Integer.parseInt(in.readLine()); s=new String [n]; System.out.println("\nEnter "+n+" strings : "); for(i=0;i<n;i++) s[i]=in.readLine(); System.out.println("\nOrginal strings"); for(i=0;i<n;i++) System.out.println(s[i]); for(i=0;i<n-1;i++) for(j=0;j<n-1;j++) { if(s[j].compareTo(s[j+1])>=0) { st=s[j]; s[j]=s[j+1]; s[j+1]=st; } } System.out.println("\nSorted strings"); for(i=0;i<n;i++) System.out.println(s[i]); } catch (Exception e) { System.out.println("Error : "+e); } } } |
Output
Enter number of strings :
5
Enter 5 strings :
sam
vinu
bipin
karthik
anoop
Orginal strings
sam
vinu
bipin
karthik
anoop
Sorted strings
anoop
bipin
karthik
sam
vinu