ADVERTISEMENT
ADVERTISEMENT

Java program to sort N names in ascending order - Sort strings Example

This program will read N strings (names) and sort them in Ascending Order.

Sorting of N Strings/Names in Ascending Order using Java program

//Java program to count words in a string.
 
import java.util.Scanner;
  
class SortStrings
{
    public static void main(String args[])
    {
        String temp;
        Scanner SC = new Scanner(System.in);
         
        System.out.print("Enter the value of N: ");
        int N= SC.nextInt();
        SC.nextLine(); //ignore next line character
         
        String names[] = new String[N];
             
        System.out.println("Enter names: ");
        for(int i=0; i<N; i++)
        {
            System.out.print("Enter name [ " + (i+1) +" ]: ");
            names[i] = SC.nextLine();
        }
             
        //sorting strings 
         
        for(int i=0; i<5; i++)
        {
            for(int j=1; j<5; j++)
            {
                if(names[j-1].compareTo(names[j])>0)
                {
                    temp=names[j-1];
                    names[j-1]=names[j];
                    names[j]=temp;
                }
            }
        }
         
         
        System.out.println("\nSorted names are in Ascending Order: ");
        for(int i=0;i<N;i++)
        {
            System.out.println(names[i]);
        }
    }
}
ADVERTISEMENT

Output

    
    Enter the value of N: 5
    Enter names: 
    Enter name [ 1 ]: Mike
    Enter name [ 2 ]: Alex
    Enter name [ 3 ]: Zoya
    Enter name [ 4 ]: Yashin
    Enter name [ 5 ]: Bobby

    Sorted names are in Ascending Order: 
    Alex
    Bobby
    Mike
    Yashin
    Zoya

Core Java Example Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.