Write a program to input forty words in an array. Arrange these words in descending order of alphabets, using the selection sort technique. Print the sorted array.
Topic: Selection sort on an array of words
Answer
import java.util.Scanner;
class SortWords { public static void main(String args[]) { Scanner sc = new Scanner(System.in); String w[] = new String[40]; String temp; int pos;
System.out.println("Enter 40 words :"); for(int i = 0; i < 40; i++) w[i] = sc.next();
for(int i = 0; i < 39; i++) { pos = i; for(int j = i + 1; j < 40; j++) { if(w[j].compareToIgnoreCase(w[pos]) > 0) pos = j; } temp = w[i]; w[i] = w[pos]; w[pos] = temp; }
System.out.println("Words in descending order :"); for(int i = 0; i < 40; i++) System.out.print(w[i] + " "); } }
Selection sort applied to Strings, which brings in one idea beyond the usual numeric version.
Strings cannot be compared with > or <. Use compareToIgnoreCase(), which returns a negative number, zero, or a positive number according to alphabetical order. Since DESCENDING order is wanted, the test looks for a word that comes LATER alphabetically: if(w[j].compareToIgnoreCase(w[pos]) > 0) For ascending order the sign would simply be reversed to < 0. That one character is the difference between the two orders.
Using compareToIgnoreCase() rather than compareTo() means "Apple" and "apple" sort together; with compareTo() every capitalised word would come before every lowercase one, since uppercase codes are lower.
The rest is the standard selection sort: track the POSITION of the best candidate in the unsorted part, then make one swap per pass using a temporary variable.
w[] String[40] - the forty words entered by the user pos int - index of the alphabetically largest word found temp String - temporary variable used during the swap i, j int - loop variables for the passes and the inner search sc Scanner - object used to read input