您的位置:首页 > 理论基础 > 数据结构算法

数据结构排序之使用JAVA范型完成2路排序

2014-03-27 20:34 337 查看
package ch10;

/**
* 2-路插入排序
* @author songjie
*
*/
public class TwoWayInsertSort {
/**
*
* @param <T>
* @param t:原始数组
* @param s:待返回的排好序的数组
* @return
* @throws IllegalArgumentException
*/
public static <T extends Comparable> boolean twoWayInsertSort(T[] t, T[] s) throws IllegalArgumentException{
if(t==null || t.length<=1) return true;//安全性检查
if(s==null || s.length!=t.length) throw new IllegalArgumentException("参数传递不正确-两个数组的长度不一样!");

s[0] = t[0];
int first = 0;
int end = 0;
for(int i=1 ; i<=t.length-1 ; i++){
if(t[i].compareTo(s[0]) > 0){//插到后面
int j;
for(j=end; j>0 && s[j].compareTo(t[i])>0 ;j--){
s[j+1] = s[j];
}
s[j+1] = t[i];
end++;
}else{//插到前面
if(first == 0){
first = s.length-1;
s[first] = t[i];
continue;
}
int k;
for(k = first; k<=s.length-1 && s[k].compareTo(t[i])<=0 ; k++){
s[k-1] = s[k];
}
s[k-1] = t[i];
first--;
}
}

return true;
}

public static void main(String[] args) {
Integer[] arr = new Integer[]{7,4,3,1,6,9,8};
Integer[] arrSort = new Integer[arr.length];
TwoWayInsertSort.twoWayInsertSort(arr, arrSort);
for(int i : arrSort){
System.out.println(i);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: