Home / Programs / Write a program to input forty words in an array. Arrange these words in descending order of alphabets, using selection sort technique. Print the sorted array.
Programming Example

Write a program to input forty words in an array. Arrange these words in descending order of alphabets, using selection sort technique. Print the sorted array.

👁 108 Views
💻 Practical Program
📘 Step by Step Learning
Study this program carefully to understand the logic, output, and explanation in a structured way.

Information & Algorithm

Given Input:


Expected Output:


Program Code

import java.util.Scanner;

public class DescendingWordSort {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] words = new String[40];
        
        // Input 40 words
        System.out.println("Enter 40 words:");
        for (int i = 0; i < 40; i++) {
            words[i] = scanner.nextLine();
        }

        // Selection sort in descending order
        for (int i = 0; i < words.length - 1; i++) {
            int maxIndex = i;
            for (int j = i + 1; j < words.length; j++) {
                if (words[j].compareTo(words[maxIndex]) > 0) {
                    maxIndex = j;
                }
            }
            // Swap the found maximum element with the first element
            String temp = words[maxIndex];
            words[maxIndex] = words[i];
            words[i] = temp;
        }

        // Print the sorted array
        System.out.println("\nWords in descending order:");
        for (String word : words) {
            System.out.println(word);
        }
        
        scanner.close();
    }
}

Output

Enter 40 words:
apple
banana
orange
grape
watermelon
kiwi
peach
strawberry
mango
pineapple
cherry
blueberry
raspberry
blackberry
papaya
guava
plum
pear
fig
apricot
nectarine
dragonfruit
pomegranate
cantaloupe
honeydew
lychee
coconut
jackfruit
avocado
lemon
lime
tangerine
mandarin
persimmon
durian
starfruit
passionfruit
mulberry
currant
elderberry
date

Words in descending order:
watermelon
tangerine
strawberry
starfruit
raspberry
pomegranate
plum
pineapple
persimmon
pear
peach
passionfruit
papaya
orange
nectarine
mulberry
mango
mandarin
lychee
lime
lemon
kiwi
jackfruit
honeydew
guava
grape
fig
elderberry
durian
dragonfruit
currant
coconut
cherry
cantaloupe
blueberry
blackberry
banana
avocado
apricot
apple
Press any key to continue . . .

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.