Startertutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.
Home » Programming » Java » Programs » Strings » Java program for sorting a given list of names in ascending order
Suryateja Pericherla Categories: Strings. No Comments on Java program for sorting a given list of names in ascending order
2.7
(11)

In this article we will learn to implement a Java program for sorting a given list of names in ascending order. A Java program is provided for sorting a given list of names or strings in ascending order.

 

Program is as follows:

import java.util.*;
class Sorting
{
	void sortStrings()
	{
		Scanner s = new Scanner(System.in);
		System.out.println("Enter the value of n: ");
		int n = s.nextInt();
		String[] str = new String[n];
		System.out.println("Enter strings: ");
		for(int i = 0; i < n; i++)
		{
			str[i] = new String(s.next());
		}
		for(int i = 0; i < n; i++)
		{
			for(int j = i+1; j < n; j++)
			{
				if(str[i].compareTo(str[j])>0)
				{
					String temp = str[i];
					str[i] = str[j];
					str[j] = temp;
				}
			}
		}
		System.out.println("Sorted list of strings is:");
		for(int i = 0; i < n ; i++)
		{
			System.out.println(str[i]);
		}
	}
}
class Driver
{
	public static void main(String[] args)
	{
		Sorting obj = new Sorting();
		obj.sortStrings();
	}
}
Java

 

Input and output for the above program are as follows:

Enter the value of n:
4
Enter strings:
suresh
mahesh
dinesh
ganesh
Sorted list of strings is:
dinesh
ganesh
mahesh
suresh
Java

 

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?


Subscribe to our monthly newsletter. Get notified about latest articles, offers and contests.


Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
Pinterest
Youtube
Instagram
Blogarama - Blog Directory