Created
October 15, 2012 07:26
-
-
Save KazumasaSUGAYA/3891196 to your computer and use it in GitHub Desktop.
基本的なアルゴリズム(ソート)の習得
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
【内容】 | |
整数が代入できるリストを作成して、リストに1~10の整数を挿入します。そのリストを昇順、降順に並び替えてみます。 | |
【SortListクラス】 | |
public class SortList { | |
public static void main(String[] args) { | |
//整数のリストを作成する | |
ArrayList<Integer> list = new ArrayList<Integer>(); | |
int max = 10; | |
for (int i = 0; i < max; i++) { | |
Random rnd = new Random(); | |
int ran = 1 + rnd.nextInt(10); // 1~10の乱数をリストに挿入します | |
list.add(i, ran); | |
System.out.println(list.get(i)); | |
} | |
Collections.sort(list); | |
System.out.println("昇順に並び替えします:" + list); | |
Collections.sort(list, new ReComparator()); | |
System.out.println("降順に並び替えします:" + list); | |
// 文字列をソートする | |
ArrayList<String> listStr = new ArrayList<String>(); | |
listStr.add("a"); | |
listStr.add("s"); | |
listStr.add("d"); | |
System.out.println(listStr); | |
Collections.sort(listStr); | |
System.out.println("アルファベット順に並び替えます:" + listStr); | |
Collections.sort(listStr, new ReComparator()); | |
System.out.println("逆アルファベット順に並び替えます:" + listStr); | |
} | |
} | |
【ReComparatorクラス】 | |
public class ReComparator implements Comparator<Object> { | |
// return値が1だと降順、-1だと昇順 | |
public int compare(Object arg0, Object arg1){ | |
return 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment