泛型归并单字段排序
package demo;
import java.util.List;
public interface GenericMergeSortI<T> {
/**
* 泛型集合归并单字段排序
* @param els 排序对象集合
* @param str 排序字段
* @param order 排序方式(asc/desc)
* @return 排序集合集合
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
List<T> MergeSort(List<T> els, String str, String order)
throws NoSuchFieldException, SecurityException,
IllegalArgumentException, IllegalAccessException;
}
package demo;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class GenericMergeSortImpl<T> implements GenericMergeSortI<T> {
@Override
public List<T> MergeSort(List<T> els, String str,String order) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
//System.out.println("开始排序");
return Sort(els,0, els.size() - 1,str,order);
}
private List<T> Sort(List<T> els, int left, int right, String str,String order) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
if (left >= right)
return null;
int mid = (left + right) / 2;
// 二路归并排序里面有两个Sort,多路归并排序里面写多个Sort就可以了
Sort(els, left, mid, str,order);
Sort(els, mid + 1, right, str,order);
return merge(els,left, mid, right, str,order);
}
private List<T> merge(List<T> els, int left, int mid, int right, String str,String order) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
List<T> tmp = new ArrayList<T>();
for (int i = 0; i < els.size(); i++) {
tmp.add(null);
}
int r1 = mid + 1;
int tIndex = left;
int cIndex = left;
// 逐个归并
while (left <= mid && r1 <= right) {
T t = els.get(left);
Field f = t.getClass().getDeclaredField(str);
f.setAccessible(true);
Object obj = f.get(t);
T t1 = els.get(r1);
Field f1 = t1.getClass().getDeclaredField(str);
f1.setAccessible(true);
Object obj1 = f1.get(t1);
if(order.equals("desc")){
if (obj instanceof Double) {
if ((Double)obj>(Double)obj1)
tmp.add(tIndex++, els.get(left++));
else
tmp.add(tIndex++, els.get(r1++));
}else if(obj instanceof Date) {
if (((Date) obj).after((Date)obj1)||((Date) obj).equals((Date)obj1))
tmp.add(tIndex++, els.get(left++));
else
tmp.add(tIndex++, els.get(r1++));
}
}else{
if (obj instanceof Double) {
if ((Double)obj<(Double)obj1)
tmp.add(tIndex++, els.get(left++));
else
tmp.add(tIndex++, els.get(r1++));
}else if(obj instanceof Date) {
if (((Date) obj).before((Date)obj1)||((Date) obj).equals((Date)obj1))
tmp.add(tIndex++, els.get(left++));
else
tmp.add(tIndex++, els.get(r1++));
}
}
}
// 将左边剩余的归并
while (left <= mid) {
tmp.add(tIndex++, els.get(left++));
}
// 将右边剩余的归并
while (r1 <= right) {
tmp.add(tIndex++, els.get(r1++));
}
// TODO Auto-generated method stub
// 从临时集合拷贝到原集合
while (cIndex <= right) {
els.remove(cIndex);
els.add(cIndex, tmp.get(cIndex));
// 输出中间归并排序结果
//System.out.print(els.get(cIndex).getTm() + "\t");
cIndex++;
}
return els;
}
}