String Sorting
Objective
To be able to use apply the bubble sort algorithm and use arrays of Strings.Task
For this lab exercise, you are to write a program that reads in a number of Strings from the user, stores them in an array, and prints them out twice, once sorted alphabetically from A-Z, and then sorted alphabetically from Z-A.
Details
- First, ask the user how many strings they will enter.
- Then create an array to hold the strings.
- You should read in the strings using a Scanner inside of a loop. You can assume the strings will not contain spaces.
- You should then write a function to sort the array using the bubble sort algorithm. The function should take an extra parameter indicating whether the array should be sorted alphabetically (A-Z) or reverse alphabetically (Z-A).
- The < and > operators do not work on strings.
Instead, you must compare them by using the compareTo String function. This returns
a negative number if the string on the left is less than the parameter, a positive one if the string on the left is greater,
and 0 if the two strings are equal. For example:
String apple = "apple"; String banana = "banana"; apple.compareTo(banana); // returns a negative number banana.compareTo(apple); // returns a positive number apple.compareTo(apple); // returns 0 - You should call this function twice, once for each option, and print the array after each.
- Your program will say that all capital letters are "less" than any lower-case letter. E.g. "Zucchini" will be alphabetically before "apple". This is due to the fact that capitals come first in the ASCII table, and is perfectly OK. Sorting according to ASCII value is called "lexicographical" sorting.
Example Run
Enter the number of strings: 5
Enter a string: pear
Enter a string: apple
Enter a string: pineapple
Enter a string: orange
Enter a string: banana
Sorted:
apple
banana
orange
pear
pineapple
Reverse sorted:
pineapple
pear
orange
banana
apple