-1

I have the following code which takes names and stores them in an ArrayList.

class Main{
  public static void main(String[] args) {
    ArrayList<String> names = new ArrayList<String>();
    Scanner scan = new Scanner(System.in);
    String name;
    do{
      System.out.println("Enter the next name: ");
      name = scan.nextLine();
      String toUpperCase = titleCase(name);
      if(!toUpperCase.equals("Stop")){
        names.add(toUpperCase);
      }
    } while(!name.equalsIgnoreCase("STOP"));

    System.out.println(names);


  }
  public static String titleCase(String s){
    String output = s.substring(0, 1).toUpperCase() +     s.substring(1).toLowerCase();
    return output;
  }

}

I need to sort the ArrayList alphabetically by name without using Collections.

2
  • Write a method sortList(List l) and implement a sorting algorithm. If this is not the expected answer: Let us know where your problem is. Commented Apr 29, 2015 at 14:31
  • 3
    No, what you need to do is: not asking other people to solve your assignments and to do the learning work for you. Commented Apr 29, 2015 at 14:32

2 Answers 2

0

String class implements Comparable<String>. Because of this you can use its compareTo method to check if any two strings are in order. Bubble sort is one of the most inefficient but probably the easiest sorting algorithm out there.

So in pseudocode, this would look like:

for int i from 0 to size of list minus two:
    if ("String at index i".compareTo("String at index i plus one") > 0)
        then swap the two strings in the list
Sign up to request clarification or add additional context in comments.

Comments

0

In Java 8 you can do

list.sort(String::compareTo);

I assume this is homework and you have to implement a sorting algorithm yourself. Which sort you use depending on what the person setting the task expects.

BTW You can use bogo sort

while(!isSorted(list)) {
    Collection.shuffle(list);
}

2 Comments

@downvoter, any reason?
I'm not the downvoter, but you can't just call list.sort(), because that method expects a Comparator.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.