Sunteți pe pagina 1din 3

4. Write a Java program to sort out a set of words in alphabetical order.

1. import java.util.Scanner;
2. public class Alphabetical_Order
3. {
4. public static void main(String[] args)
5. {
6. int n;
7. String temp;
8. Scanner s = new Scanner(System.in);
9. System.out.print("Enter the number of names:");
10. n = s.nextInt();
11. String names[] = new String[n];
12. Scanner s1 = new Scanner(System.in);
13. System.out.println("Enter all the names:");
14. for(int i = 0; i < n; i++)
15. {
16. names[i] = s1.nextLine();
17. }
18. for (int i = 0; i < n; i++)
19. {
20. for (int j = i + 1; j < n; j++)
21. {
22. if (names[i].compareTo(names[j])>0)
23. {
24. temp = names[i];
25. names[i] = names[j];
26. names[j] = temp;
27. }
28. }
29. }
30. System.out.print("Names in Sorted Order:");
31. for (int i = 0; i < n - 1; i++)
32. {
33. System.out.print(names[i] + ",");
34. }
35. System.out.print(names[n - 1]);
36. }
37. }

Output:
$ javac Alphabetical_Order.java
$ java Alphabetical_Order

Enter the number of names :5


Enter all the names:
bryan
adam
rock
chris
scott
Names in Sorted Order:adam,bryan,chris,rock,scott

Java code to arrange the letters of a


word in alphabetical order
Java program to arrange the letters of a word in alphabetical order.

import java.io.*;
class AlphabeticalOrder
{
static String n;
static int l;
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a word : ");
n = br.readLine();
l = n.length();
alphabetical();
}
public static void alphabetical()
{
char b[] = new char[l];
for(int i=0;i<l;i++)
b[i] = n.charAt(i);
char t;
for(int j=0;j<l-1;j++)
{
for(int k=0;k<l-1-j;k++)
{
if(b[k]>b[k+1])
{
t=b[k];
b[k]=b[k+1];
b[k+1]=t;
}
}
}
System.out.println("\nOriginal word : " +n);
System.out.print("Sorted word : ");
for(int m=0;m<l;m++)
System.out.print(b[m]);
System.out.print("\n");
}
}

ALGORITHM:-

1. Start

2. Accept a word from the user.

3. Convert each letter of the word to its corresponding ASCII value.

4. Compare each letter of the word by its next letter and swap them if the first letter has a greater ASCII
value than the next one.

5. Repeat the above procedure until the entire word is sorted.

6. Print the new word.

7. End

OUTPUT:-

Enter a word : computer

Original word : computer

Sorted word : cemoprtu

S-ar putea să vă placă și