2016-11-06 31 views
0
/** 
* Sorts the list of players alphabetically by name. 
* Adapt insertion sort algorithm. 
* You can assume that no two players have the same name. 
* Question T1. Adapting insertion sort for this method 
* could yield efficiencies relative to some other approaches 
* for some important special cases. 
* Do you agree and if so why? Write about 6 to 10 lines. 
*/ 
public void alphabeticSort() { 
    Player temp; 

    for (int i = 0; i < players.size(); i++) { 
     for (int j = players.size() - 1; j > i; j--) 
      if (players.get(i).compareTo(players.get(j)) < 0) { 

       temp = players.get(i); 
       players.set(i, players.get(j)); 
       players.set(j, temp); 
      } 
     } 
    } 

我一直在努力,努力,但我有一些困難,試圖比較,你不能使用<><Player>ArrayList類。我們也無法使用任何Collection.sort導入。排序<Player> ArrayList的名稱的字母順序

一個正確的方向將是巨大的!

回答

2

如果你想通過名稱來比較的球員,那麼對象通過他們的名字比較:如果你允許使用Collections.sort

if (players.get(i).getName().compareTo(players.get(j).getName()) < 0) { 

,則實現可能是一個非常簡單並且更好:

public void alphabeticSort() { 
    Collections.sort(players, (p1, p2) -> p1.getName().compareTo(p2.getName())); 
} 
+0

排序列表,你想使用集合。使用自定義比較器排序()而不是自己編碼... –

+0

似乎他不允許使用'Collections.sort' – janos

+0

感謝您的幫助janos。現在就開始工作吧! – copernicon1543

1

您可以使用Java 8 Lambda按字母順序按名稱排序。它會更簡潔。

以下面的代碼爲例 -

public class Test { 
    public static void main(String[] args) { 
     List<Person> list = new ArrayList<>(Arrays.asList(new Person("seal", 25), new Person("tomcat", 32) 
       , new Person("Alpha", 15))); 

     // using Java 8 lambda to sort 
     // you could use this portion inside your alphabeticSort() method. 
     List<Person> newList = list.stream() 
       .sorted(Comparator.comparing(i -> i.getName())) 
       .collect(Collectors.toList()); 

     // for printing 
     newList.stream() 
       .forEach(System.out::println); 

    } 

    static class Person { 
     String name; 
     int age; 

     public Person(String name, int age) { 
      this.name = name; 
      this.age = age; 
     } 

     public String getName() { 
      return name; 
     } 

     public int getAge() { 
      return age; 
     } 
    } 
} 

所以,你的``方法可能看起來會返回基於名字 -

public List<Person> alphabeticSort(List<Person> list) { 
    return list.stream() 
      .sorted(Comparator.comparing(i -> i.getName())) 
      .collect(Collectors.toList()); 
}