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.

Java Programming Language (Article) (Program)

23

Given Input:


Expected Output:


Program:

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 . . .


This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.