Write a Java Program to Sort n Strings in Alphabetical Order

By | 04.03.2017

Java Program to Sort n Strings


Write a Java Program to Sort n Strings in Alphabetical Order, you have to ask to the user to enter the two string, now start comparing the two strings, if found then make a variable say temp of the same type, now place the first string to the temp, then place the second string to the first, and place temp to the second string and continue.

Following Java Program ask to the user to enter any n string like names to sort them in alphabetical order then display the sorted string in alphabetical order on the screen:


SOURCE CODE : :


import java.util.Scanner;

public class SortStrings
{
    public static void main(String[] input)
    {
        int i, j,n,c=1;
        String temp;
        Scanner scan = new Scanner(System.in);
        
        System.out.print("Enter no. of Strings u want to Sort : ");
        n=scan.nextInt();
        
        String names[] = new String[n];
                
        System.out.println("Enter "+ n + " Strings : \n");
        for(i=0; i<n; i++)
        {
            System.out.print("Enter " + c + " String : ");
            names[i] = scan.next();
            c++;
        }
                
                
        System.out.println("\nSorting Strings in Alphabetical Order...\n");
        for(i=0; i<n; i++)
        {
            for(j=1; j<n; j++)
            {
                if(names[j-1].compareTo(names[j])>0)
                {
                    temp=names[j-1];
                    names[j-1]=names[j];
                    names[j]=temp;
                }
            }
        }
        
        for(i=0;i<n;i++)
        {
            System.out.println(names[i]);
        }
    }
}

 

OUTPUT : :

 

Enter no. of Strings u want to Sort : 8
Enter 8 Strings : 

Enter 1 String : abc
Enter 2 String : swd
Enter 3 String : r
Enter 4 String : fda
Enter 5 String : yhg
Enter 6 String : tree
Enter 7 String : uhju
Enter 8 String : yrf

Sorting Strings in Alphabetical Order...

abc
fda
r
swd
tree
uhju
yhg
yrf

 

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments