算法优解(9)-单链表的选择排序

本文介绍了一种在无序单链表上实现选择排序的方法,该方法通过不断寻找当前未排序部分的最小元素并将其移至已排序部分的末尾来完成排序过程。额外空间复杂度为O(1),并提供了完整的Java实现代码及运行示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

来自左神书中的一道题,在左神核心代码的基础上,添加了链表的构建和打印操作,将这道题完善成了一个小Demo,和各位共勉。

题目:

给定一个无序单链表的头结点head,实现单链表的选择排序。

要求额外空间复杂度O(1)。


思路:

从未排序链表中找到最小节点small的前一节点smallPre,从而在未排序链表中删除最小节点small,并将最小节点small添加到已排序链表中,由此逐渐缩小未排序链表,实现链表的选择排序。


核心算法:

最小节点small的前一节点smallPre:

public static Node getSmallPreNode(Node head){
		Node small = head;
		Node smallPre = null;
		Node pre = head;
		Node cur = head.next;
		
		while(cur != null){			
			if(cur.value < small.value){
				small = cur;
				smallPre = pre;
			}
			pre = cur;
			cur = cur.next;
		}
		
		return smallPre;
	}

选择排序链表:

	public static Node SelectionSort(Node head){
		Node cur = head;
		Node small = null;
		Node smallPre = null;
		
		Node tail = null;

		while(cur != null){
			small = cur;
			smallPre = getSmallPreNode(cur);
			if(smallPre != null){
				small = smallPre.next;
				smallPre.next = small.next;
			}
			cur = cur == small ? cur.next : cur;
			if(tail == null){
				head = small;
			}else{
				tail.next = small;
			}
			tail = small;
		}
		return head;
	}

原创不易,转载请注明出处哈。

权兴权意

http://blog.youkuaiyun.com/hxqneuq2012/article/details/53190574


完整源代码:

public class SelectionSortTest {

	/**
	 * 权兴权意-2016.11.10
	 * 单链表的选择排序
	 */
	public static void main(String[] args) {
		//构建链表5-0
		Node head1 = new Node(5);
		Node temp1 = head1;
		for(int i = 4;i > 0;i--){
			temp1.next = new Node(i);
			temp1 = temp1.next;
		}
		
		printList(head1);
		head1 = SelectionSort(head1);
		printList(head1);
		
	}
		
	public static Node SelectionSort(Node head){
		Node cur = head;
		Node small = null;
		Node smallPre = null;
		
		Node tail = null;

		while(cur != null){
			small = cur;
			smallPre = getSmallPreNode(cur);
			if(smallPre != null){
				small = smallPre.next;
				smallPre.next = small.next;
			}
			cur = cur == small ? cur.next : cur;
			if(tail == null){
				head = small;
			}else{
				tail.next = small;
			}
			tail = small;
		}
		return head;
	}
	
	public static Node getSmallPreNode(Node head){
		Node small = head;
		Node smallPre = null;
		Node pre = head;
		Node cur = head.next;
		
		while(cur != null){			
			if(cur.value < small.value){
				small = cur;
				smallPre = pre;
			}
			pre = cur;
			cur = cur.next;
		}
		
		return smallPre;
	}
	
	//打印链表
	public static void printList(Node head){
		Node temp = head;
		while(temp != null){
			if(temp.next == null){
				System.out.print(temp.value + " ");
				break;
			}
			System.out.print(temp.value + "->");
			temp = temp.next;
		}
		System.out.println();
	}

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值