比方说画面上有一些纪录,然后有一个上移动和下移动的按钮No. Name 1 aaa
2 bbb
3 ccc
3 ddd
3 fff
4 hhh
5 ggg如果我选中3个no.为3的纪录中的随便一条,点下移动按钮,要变成如下效果1 aaa
2 bbb
3 hhh
4 ccc
4 ddd
4 fff
5 ggg
总的来说,就是no.一样的纪录需要连着一起换位置。。
2 bbb
3 ccc
3 ddd
3 fff
4 hhh
5 ggg如果我选中3个no.为3的纪录中的随便一条,点下移动按钮,要变成如下效果1 aaa
2 bbb
3 hhh
4 ccc
4 ddd
4 fff
5 ggg
总的来说,就是no.一样的纪录需要连着一起换位置。。
每条记录有个index属性用来记录索引位置,把所有index原值为i的记录index变为k(上移下移只是特例而已),其他记录的index跟着变,这里的逻辑很简单就不说了
然后再按index排序
public class Test {
static int[] index = new int[]{1,2,3,3,3,4,5};
static String[] value = new String[]{"aaa","bbb","ccc","ddd","fff","hhh","ggg"};
static Item[] item = new Item[index.length];
public static void main(String[] args) {
for(int i = 0;i < index.length;i++){
item[i] = new Item(index[i],value[i]);
}
System.out.println("原始序列:");
print(item);
moveDown(item,3);
System.out.println("向下移动后排序:");
item = sort(item,3);
print(item);
} public static void moveDown(Item[] item,int n){
for (int i = 0;i < item.length;i++){
if(item[i].index == n){
item[i].index = n + 1;
}
else if(item[i].index == n + 1){
item[i].index = n;
}
}
}
public static Item[] sort(Item[] item,int n){
Item[] newItem = new Item[item.length];
int start = 0,end = 0;
for(int i = item.length - 1;i >= 0 ;i--){
if(item[i].index == n + 1){
start = i;
break;
}
}
for(int i = item.length - 1;i >= 0 ;i--){
if(item[i].index == n){
end = i;
break;
}
}
int m = start,index = 0;
for(int i = 0;i < item.length;i++){
if(item[i].index < n || item[i].index > n + 1){
newItem[i] = item[i];
}
if(item[i].index < n){
index = i;
}
}
int oldIndex = index;
for(int i = m;i < end;i++){
newItem[++index] = item[++m];
}
for(int i = index;i < end;i++){
newItem[++index] = item[++oldIndex];
}
return newItem;
}
public static void print(Item[] item){
for(int i = 0;i < item.length;i++){
System.out.println(item[i].index + " " + item[i].value);
}
}
static class Item{
int index;
String value;
public Item(int index,String value){
this.index = index;
this.value = value;
}
}
}
原始序列:
1 aaa
2 bbb
3 ccc
3 ddd
3 fff
4 hhh
5 ggg
向下移动后排序:
1 aaa
2 bbb
3 hhh
4 ccc
4 ddd
4 fff
5 ggg