I have a project for class were I need to get 4 different strings inputted and then output them in alphabetical order.
So far I have this:
String wd1
Typical divide and concur strategy could be applied. Think about merge sort, sort first 2 and last 2 strings, after that merge results.
if(s2<s1) swap(s1,s2)
if(s4<s3) swap(s3,s4)
if(s1<s3) {
print(s1)
if(s2<s3){
print(s2)
print(s3)
print(s4)
} else {
print(s3)
if(s2<s4){
print(s2)
print(s4)
} else {
print(s4)
print(s2)
}
}
} else {
print(s3)
if(s4<s1){
print(s4)
print(s1)
print(s2)
} else {
print(s1)
if(s4<s2){
print(s4)
print(s2)
} else {
print(s2)
print(s4)
}
}
}
How about putting the Strings in a List
and call the sort()
method?
The Java String class implements the 'Comparable' interface and thus already has the compareTo()
method, which should compare the strings in order.
boolean swapped = false;
do {
swapped = false;
if (w2.compareTo(w1) < 0) {
String tmp = w2;
w2 = w1;
w1 = tmp;
swapped = true;
}
if (w3.compareTo(w2) < 0) {
String tmp = w3;
w3 = w2;
w2 = tmp;
swapped = true;
}
if (w4.compareTo(w3) < 0) {
String tmp = w4;
w4 = w3;
w3 = tmp;
swapped = true;
}
} while (swapped)
System.out.println(w1);
System.out.println(w2);
System.out.println(w3);
System.out.println(w4);
For comparing more than 2 strings you should put the strings in an array and then run them through a sorting method
public class SortLetters2 {
public String[] sort(String[] asd) {
String[] sorted = asd.clone();
for (int i = 0; i < sorted.length; i++) {
for (int j = i + 1; j < sorted.length; j++) {
int compare = sorted[i].compareTo(sorted[j]);
if ((compare > 0) && (i != j)) {
//compare two strings
String temp = sorted[j];
sorted[j] = sorted[i];
sorted[i] = temp;
}
}
}
return sorted;
}
public static void main(String[] args) {
SortLetters2 list1 = new SortLetters2();
//SortLetters2 is the class name
Scanner scan1 = new Scanner(System.in);
String wd1, wd2, wd3, wd4;
System.out.println("Type Word One: ");
wd1 = scan1.next();
System.out.println("Type Word Two: ");
wd2 = scan1.next();
System.out.println("Type Word Three: ");
wd3 = scan1.next();
System.out.println("Type Word Four: ");
wd4 = scan1.next();
String array[] = {wd1, wd2, wd3, wd4};
//set array equal to the inputs
String[] sortedArray = list1.sort(array);
for (int i = 0; i < sortedArray.length; i++) {
if (i == sortedArray.length - 1) {
System.out.println(sortedArray[i]);
} else {
System.out.print(sortedArray[i] + ",");
}
}
//run sorting program
}
}
You need to compare first string with the rest three to find which is alphabetically first. after that you need to compare among the rest 3 and so on.
The easiest way to do what you are looking for is to put them in a list, then use list.sort() to put them in order.