简体   繁体   中英

How to sort an arraylist alphabetically without using collections.sort();

I have the following code, and I have sort the array list alphabetically in the main method, as the user inputs his strings. Here is my code:

import java.util.Scanner;
import java.util.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.toString());


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

Please don't give any generic answers, I've been struggling with this for a while now. If the answer seems simple to you, it probably isn't for me.

replace this line:

names.add(toUpperCase);

with this:

int index = names.size();
for (int i = 0; i < names.size(); i++) {
    if (names.get(i).compareTo(toUpperCase) > 0) {
        index = i;
        break;
    }
}
names.add(index, toUpperCase);

so, every time you have new string from user - you will insert it into proper position of your array list

this method is quite slow, but ok for home assignment

As suggested in the comments, the most simple way of maintaining a sorted data structure upon each insert is to use a TreeSet or any other data structure that maintains sorted order internally. Instead of declaring an ArrayList<String> you would simply need to modify your code to this:

Set<String> names = new TreeSet<>();
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"));

From Javadocs for TreeSet:

the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

Please try below code. You can replace the sorting algorithm with more efficient algorithm like merge sort/selection sort etc..

import java.util.Scanner;
import java.util.ArrayList;

class alsort{
  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.toString());

    for(int i=0;i<name.length();i++){
        for(int j=i;j<=name.length();j++){
            if(names.get(i).compareTo(names.get(j))>0){
                String tmp=names.get(i);
                names.set(i, names.get(j));
                names.set(j, tmp);
            }
        }
    }

    System.out.println(names.toString());


  }
  public static String titleCase(String s){
    String output = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
    return output;
  }
}
public class SortedArrayList<T> extends ArrayList<T> {

        /**
     * 
     */
    private static final long serialVersionUID = 1L;


        @SuppressWarnings("unchecked")
        public void insertSorted(T value) {
            add(value);
            Comparable<T> cmp = (Comparable<T>) value;
            for (int i = size()-1; i > 0 && cmp.compareTo(get(i-1)) < 0; i--)
                Collections.swap(this, i, i-1);
        }


    public static void main(String[] s){        
        SortedArrayList<String> myList = new SortedArrayList<String>();

        myList.insertSorted("ddd");   
        myList.insertSorted("aaa");
        myList.insertSorted("xyz"); 
        System.out.println(myList);     
    }



}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM