package test;
import java.util.List;
public class Collections {
public static void sort(List list){
int l = 0;
int r = list.size()-1; //list中的元素个数
//归并
devide(list,l,r);
}
/**
* 归:分治
*/
private static void devide(List list,int left,int right){
//归
int mid = (left+right)/2;
if (left < right){
devide(list,left,mid);
devide(list,mid+1,right);
//并
merge(list,left,mid,mid+1,right);
}
// else {
// //并
// merge(list,left,mid,mid+1,right);
// }
}
/**
* 并
* @param list
* @param left
* @param mid
* @param i
* @param right
*/
private static void merge(List list, int left, int mid, int i, int right) {
Object[] temp =new Object[list.size()];
int index = left; //temp数组的起始索引
int ls = left,le = mid; //ls 左边的起始索引,le左边的结束索引
int rs = i, re = right; //rs 右边的起始索引,re 右边的结束索引
//至少把一边的数组元素排好,放入临时数组
while (ls <= le && rs <= re){
Comparable o1 = (Comparable) list.get(ls);
Comparable o2 = (Comparable) list.get(rs);
if (o1.compareTo(o2) == -1){
//表示o1 < o2
temp[index] = o1;
ls++;
}
else {
temp[index] = o2;
rs++;
}
index++;
}
//判断左边元素是否有剩余
if (ls <= le){
for (int j = ls; j<=le; j++)
{
temp[index++] = list.get(j);
}
}
//判断右边元素是否有剩余
if (rs <= re){
for (int j = rs; j<=re; j++)
{
temp[index++] = list.get(j);
}
}
for (int j=left; j<=right; j++)
{
list.set(j,temp[j]);
}
}
}
//测试
public void test3(){
List s = new ArrayList();
s.add(new Student(111,"A"));
s.add(new Student(123,"B"));
s.add(new Student(12,"L"));
test.Collections.sort(s);
System.out.println(s);
}
归并排序 -- Comparable接口实现
于 2019-06-11 23:03:07 首次发布