-
Die Bubblesort
OK so I have to make this program where it takes input (names) from the user. The names are strings of course. The names are entered into an array where a bubblesort method dealy then sorts them alphabetically. I have it so that It will takes names from the user and puts them in an array but I have not the slightest clue on how to sort them. I have some sort of pseudo code kind of deal going on at the bottom.
import java.util.Scanner;
Code:
public class NameList
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int listLength, index = 0;
String[] nameList;
String nameIndex;
System.out.print("How many names? ");
listLength = scan.nextInt() + 1;
nameList = new String[listLength];
while (index < listLength)
{
nameIndex = scan.nextLine();
nameList[index] = nameIndex;
System.out.print("=> ");
index++;
}
for (int k = nameList.length - 2; k > 1; k--)
{
for (int j = k; nameList[j] < nameList[j + 1]; j++)
{
swap(nameList[j], nameList[j + 1]);
}
}
}
}
-
You can't use < for comparing strings. Use the compareTo method.
Then you obviously also need to implement that swap method (that should be simple enough).
Also make sure to understand the algorithm.
-
Thanks but I ended up just using
Arrays.sort(nameList);
Does the same thing. Screw bubblesort;