Home »
Java Programs »
Core Java Example Programs
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]);
}
}
}
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 »