Written by Sai Sameera Thota on June 21, 2013 in Java > Programming

Java Program to Sort given list of Names in Ascending order

GET ALERTS:

Get our Latest updates delivered to your mailbox!

Have a huge list of Names and you need to sort them alphabetically? What will you do? We simply write a Java program to achieve this in few seconds. This Java Program helps you to sort given list of names in ascending order.

The program takes n number of names as input and returns the names in a sorted order. It uses compareToIgnoreCase method of java to sort the given names. The method compares two strings lexicographically, ignoring the case differences and returns an integer value.

Consider two strings str1 and str2.

int result = srt1.compareToIgnoreCase(str2);
If str1 is less than str2, the method will return a negative value.
If str1 is greater than str2, the method will return a positive value and if
str1 is equal to str2, the method will return 0.

Java Program to Sort given list of Names in Ascending Order

import java.io.*;
class SortingNames
{
	public static void main(String[] args) throws IOException
	{
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			System.out.print("\nEnter The number of Names :");
			int n = Integer.parseInt(br.readLine());
			String names[] = new String[n];
			System.out.println();
			for (int i = 1; i <= n; i++)
			{
				System.out.print("Enter Name " + i + ":");
				names[i-1] = br.readLine();
			}
			System.out.println("\nNames in Ascending Order");
			System.out.println();
			for (int j = 0; j < names.length; j++)
			{
				for (int i = j + 1; i < names.length; i++)
				{
					if (names[i].compareToIgnoreCase(names[j]) < 0)
					{
						String temp = names[j];
						names[j] = names[i];
						names[i] = temp;
					}
				}
				System.out.println(names[j]);
			}
	}
}

Output:
Java program to Sort given list of Names in Ascending order

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: