I have been going around and around on this and I'm finally coming here because it seems like my code is working properly. Below is my input and output:
Input:
Task
Enter
twenty
words
from
the
keyboard
and
Display
them
In
alphabetical
order
Each
word
Should
be
on
new
line
Output:
alphabetical
and
be
Display
Each
Enter
from
In
keyboard
line
new
on
order
Should
Task
the
them
twenty
word
words
package com.codegym.task.task08.task0830;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
/*
Task about algorithms
*/
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
//String[] array = new String[]{"Task", "Enter", "twenty", "words", "from", "the", "keyboard", "and", "Display", "them", "In", "alphabetical", "order", "Each", "word", "Should", "be", "on", "new", "line"};
String[] array = new String[20];
for (int i = 0; i < array.length; i++) {
array[i] = reader.readLine();
}
sort(array);
for (String x : array) {
System.out.println(x);
}
}
public static void sort(String[] array) {
//write your code here
//Arrays.sort(array);
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
String temp = array[i];
int b = 0;
int e = 1;
String s1 = array[i].substring(b, e).toLowerCase();
String s2 = array[j].substring(b, e).toLowerCase();
if (s1.equals(s2)) {
while (s1.equals(s2) && array[i].length() > e && array[j].length() > e) {
b++;
e++;
s1 = array[i].substring(b, e);
s2 = array[j].substring(b, e);
}
if (array[i].length() == e || array[j].length() == e) {
if (array[i].length() > array[j].length()) {
array[i] = array[j];
array[j] = temp;
b = 0;
e = 1;
}
}
else if (isGreaterThan(s1, s2)) {
array[i] = array[j];
array[j] = temp;
b = 0;
e = 1;
}
}
else if (isGreaterThan(s1, s2)) {
array[i] = array[j];
array[j] = temp;
b = 0;
e = 1;
}
}
}
}
// String comparison method: 'a' is greater than 'b'
public static boolean isGreaterThan(String a, String b) {
return a.compareTo(b) > 0;
}
}