Q&A ICSE2017-09A #7266
Question:
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.
Answer:
import java.util.Scanner;
public class SelectionSort {
public static void main(String[] args) {
// Accept 40 words
Scanner scanner = new Scanner(System.in);
String[] words = new String[40];
System.out.println("Enter 40 words: ");
for (int i = 0; i < 40; i++) {
words[i] = scanner.nextLine();
}// Sort using selection sort
for (int i = 0; i < words.length - 1; i++) {
int largestWordIndex = i;
for (int j = i + 1; j < words.length; j++) { 20 if (words[j].compareTo(words[largestWordIndex]) > 0) {
largestWordIndex = j;
}
}
String temp = words[largestWordIndex];
words[largestWordIndex] = words[i];
words[i] = temp;
}
// Print sorted array
for (int i = 0; i < 40; i++) {
System.out.println(words[i]);
}
}
}
