I want to sort values of an array in alphabetic order, using merge sort. I have this code so far, but I when I run it, the output is jumbled and not in correct order. (Charlottetown, Fredericton, Montreal, Toronto, Vancouver, …)
If anyone has any advice/solutions, I would appreciate your help 🙂
Here is my current code.
class Main {
public static void main(String[] args) {
String [] words = {"Montreal", "Halifax", "Toronto", "Vancouver",
"Whitehorse", "Winnipeg", "Calgary", "Edmonton",
"Hamilton", "Regina", "Saskatoon", "Sault Ste. Marie", "Moncton", "Gander", "Fredericton", "Charlottetown"};
for(int i = 0; i < words.length; i++)
{
int smallest = i;
for(int j = i + 1; j < words.length; j++)
{
if(words[j].compareTo(words[i]) < 0)
smallest = j;
}
String aux = words[i];
words[i] = words[smallest];
words[smallest] = aux;
}
for(int i = 0; i < words.length; i++)
{
System.out.println(words[i]);
}
}
}