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();
}
}
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 . . .
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.