Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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]);
        }
    }
}

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Core Java Example programs for Beginners and Professionals

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to count total number of words in a s... >>
<< Java program to count divisors of an integer numbe...