Code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the number of string you want to sort: "); int n = sc.nextInt(); String str[] = new String[n]; String temp; int i, j; System.out.println("Enter all strings:"); for(i = 0; i < str.length; i++) { str[i] = sc.next(); } for(i = 0; i < str.length; i++) { for(j = i + 1; j < str.length; j++) { if((str[i].compareTo(str[j])) > 0) { temp = str[i]; str[i] = str[j]; str[j] = temp; } } } System.out.println("\nSorted strings:"); for(i = 0; i < str.length; i++) { System.out.println(str[i]); } }}
Output:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of string you want to sort: ");
int n = sc.nextInt();
String str[] = new String[n];
String temp;
int i, j;
System.out.println("Enter all strings:");
for(i = 0; i < str.length; i++)
{
str[i] = sc.next();
}
for(i = 0; i < str.length; i++)
{
for(j = i + 1; j < str.length; j++)
{
if((str[i].compareTo(str[j])) > 0)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
System.out.println("\nSorted strings:");
for(i = 0; i < str.length; i++)
{
System.out.println(str[i]);
}
}
}
Tags:
Java Programs