Java 拖拽排序

向前移动

image

将元素D移到B前面,分2步:

  • D放到 index=1 的位置
  • B和D中间的元素向后移动1个位置

向后移动

image

将元素B移到D后面,分2步:

  • B放到 index=3 的位置
  • B和D中间的元素向前移动1个位置

代码实现

public static void main(String[] args) {
	List<String> sourceList = Arrays.asList("A", "B", "C", "D", "E");
	// 移动元素、被替换元素的下标
	int targetIdx = 3, replaceIdx = 1;
	// 向前或后移动
	boolean forward = true;
	// 放入链表
	LinkedList<String> linkedList = new LinkedList<>(sourceList);
	// 目标元素和被替换元素更换位置
	linkedList.set(replaceIdx, sourceList.get(targetIdx));
	// 如果向前移动,则被替换和后面的都往后移动
	if (forward) {
		for (int i = replaceIdx + 1; i <= targetIdx; i++) {
			linkedList.set(i, sourceList.get(i - 1));
		}
	} else {
		// 如果向后移动,则被替换和后面的都往前移动
		for (int i = targetIdx; i < replaceIdx; i++) {
			linkedList.set(i, sourceList.get(i + 1));
		}
	}
	linkedList.forEach(a -> System.out.println(a));
}
posted @ 2024-01-03 14:07  艺言弈行  阅读(164)  评论(0编辑  收藏  举报