常见有选择排序和冒泡排序: 时间复杂度都是O(n^2)
public void sort1(ArrayList<Integer> list){//冒泡:效率较慢,因为就算找到最大的也要进if挨个比较移动位置
for (int i = 0; i < list.size() - 1; i++){
for (int j = 1; j < list.size() - i; j++){
if (list.get(j - 1) > list.get(j)){
int temp = list.get(j);
list.set(j, list.get(j - 1));
list.set(j - 1, temp);
}
}
}
}
public void sort(ArrayList<Integer> list){//选择排序:效率较快,一旦找到最大的直接记录最大的角标,不需要再进if
int temp = 0;
int maxIndex = 0;
for (int i = 0; i < list.size() - 1; i++){
maxIndex = i;
for (int j = i + 1; j < list.size(); j++){
if (list.get(maxIndex) > list.get(j)){
maxIndex = j;
}
}
if (i != maxIndex){
temp = list.get(i);
list.set(i, list.get(maxIndex));
list.set(maxIndex, temp);
}
}
}
还有其他排序方法,堆排序(利用2叉树)O(nlogn),递归排序等
根据对象属性排序的几种方法
Collections.sort(List<T> list); sort(List<T>)方法中List中的T必须实现Comparable<T>接口
Collections提供的第二种排序方法sort(List<T> list, Comparator<? super T> c),临时排序
Collections.sort(students, new Comparator<Students>() { @Override public int compare(Students o1, Students o2) { int i = o1.getScore() - o2.getScore(); if(i == 0){ return o1.getAge() - o2.getAge(); } return i; } });根据多个属性排序
/**
* List 元素的多个属性进行排序。例如 ListSorter.sort(list, "name", "age"),则先按
* name 属性排序,name 相同的元素按 age 属性排序。
*
* @param list 包含要排序元素的 List
* @param properties 要排序的属性。前面的值优先级高。
*/
public
static
<V>
void
sort(List<V> list,
final
String... properties) {
Collections.sort(list,
new
Comparator<V>() {
public
int
compare(V o1, V o2) {
if
(o1 ==
null
&& o2 ==
null
)
return
0
;
if
(o1 ==
null
)
return
-
1
;
if
(o2 ==
null
)
return
1
;
for
(String property : properties) {
Comparator c =
new
BeanComparator(property);
int
result = c.compare(o1, o2);
if
(result !=
0
) {
return
result;
}
}
return
0
;
}
});
}
}