极客时间-排序-插入排序(链表实现)

import java.util.Random;

public class LinkInsert {

	public Node head;
	private Integer num;

	public void init(int num, Node node) {
		this.num = num;
		this.head = node;
	}

	class Node {
		private Integer data;
		private Node next;
	}

	/* 使用尾插发创建链表 */
	public void createLink() {
		Random random = new Random(1);
		Node tail = head;
		Integer datas[] = { 10, 25, 19, 26, 5, 25, 27, 19, 1, 20 };
		for (int i = 0; i < num; i++) {
			/* Integer data=(int) (1+Math.random()*(30-1)); */
			System.out.print(datas[i] + " ");
			Node newNode = new Node();
			newNode.data = datas[i];
			tail.next = newNode;
			tail = newNode;
		}

		insertSort();

	}

	/*
	 * 插入排序: 1.把数组分为两部分,有序的和无序的
	 * 2.依次从无序中取出元素和排序好的序列比较,如果找到比它小的元素依次往前寻找,直到找到大于等于此元素的位置,从这个位置插入(链表不需要移动)
	 * 3.把该元素插入到有序序列中 4.直到无序序列中元素取完为止
	 */
	public void insertSort() {
		if (head.next != null && head.next.next != null) {// 只有一个元素
			Node nosorttail = head.next.next;
			Node preNoSortNode = head.next;
			for (int i = 1; i < num; i++) {
				Node sorttail = head;
				Integer data1 = nosorttail.data;//外层循环无序当中取出元素
				boolean isflag = false;
				for (int j = 0; j < i; j++) {// 把取出节点和有序序列节点从头开始依次比较
					Node preSortNode = sorttail;//记录当前有序序列中比较元素的上一个节点
					sorttail = sorttail.next;//有序序列中当前比较节点
					Integer data2 = sorttail.data;//有序序列中当前节点的值
					if (data1 < data2) {// 插入到比从无序中取出节点值大的前面
						preNoSortNode.next = nosorttail.next;
						preSortNode.next = nosorttail;
						nosorttail.next = sorttail;
						isflag = true;
						break;
					}
				}

				if (!isflag) {//如果没有发生插入,说明无序节点元素所在位置就是它应该在的位置
					preNoSortNode = nosorttail;//记录当前节点作为下一次从无序中取出节点的上一个节点
					nosorttail = nosorttail.next;//把无序序列中指针指向下一个节点
				} else {//如果发生了插入,无序节点等于上一个无序节点的下一个节点
					nosorttail = preNoSortNode.next;
				}

				// 每次排序结果输出
				Node outNode = head.next;
				outPrint(outNode, i);
			}

		}

	}

	public void outPrint(Node node, int i) {
		System.out.print("\n第" + i + "次排序得到");
		while (node != null) {
			System.out.print(node.data + " ");
			node = node.next;
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		LinkInsert link = new LinkInsert();
		link.init(10, link.new Node());
		link.createLink();

	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值