📅  最后修改于: 2023-12-03 15:11:15.924000             🧑  作者: Mango
本文介绍的是一种用于单链表递归选择排序的Python程序,该程序采用“交换节点链接”的方式实现排序,具有时间复杂度为O(n^2)的优点。
下面是该程序的Python代码实现:
class Node:
def __init__(self, data=None):
self.data = data
self.next_node = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
last_node = self.head
while last_node.next_node:
last_node = last_node.next_node
last_node.next_node = new_node
def swap(self, node1, node2):
curr_node = self.head
prev_node1 = None
prev_node2 = None
while curr_node:
if curr_node == node1:
temp = node2.next_node
node2.next_node = node1.next_node
if prev_node1:
prev_node1.next_node = node2
else:
self.head = node2
node1.next_node = temp
prev_node2.next_node = node1
return
elif curr_node == node2:
temp = node1.next_node
node1.next_node = node2.next_node
if prev_node2:
prev_node2.next_node = node1
else:
self.head = node1
node2.next_node = temp
prev_node1.next_node = node2
return
else:
prev_node1 = curr_node if curr_node.next_node == node1 else prev_node1
prev_node2 = curr_node if curr_node.next_node == node2 else prev_node2
curr_node = curr_node.next_node
def get_min_node(self, start_node):
min_val = start_node.data
min_node = start_node
curr_node = start_node.next_node
while curr_node:
if curr_node.data < min_val:
min_val = curr_node.data
min_node = curr_node
curr_node = curr_node.next_node
return min_node
def recursive_sort(self, curr_node=None):
if curr_node is None:
curr_node = self.head
if curr_node.next_node is None:
return
min_node = self.get_min_node(curr_node)
if curr_node != min_node:
self.swap(curr_node, min_node)
self.recursive_sort(curr_node.next_node)
def print_list(self):
curr_node = self.head
while curr_node:
print(curr_node.data)
curr_node = curr_node.next_node
要使用该程序,需要定义一个LinkedList
对象,然后向其中添加节点数据。添加完成后,可以调用recursive_sort
方法进行排序,最后使用print_list
方法输出排序后的链表数据。例如:
linked_list = LinkedList()
linked_list.append(3)
linked_list.append(1)
linked_list.append(4)
linked_list.append(2)
linked_list.append(5)
linked_list.recursive_sort()
linked_list.print_list()
运行结果为:
1
2
3
4
5
该程序使用递归方式实现选择排序。每次递归中,找到当前节点之后的最小值节点,如果该节点不是当前节点本身,则交换两个节点的链接。通过这种方式,每次递归将排序完当前节点之后的子链表。递归结束后,整个链表将被排序完成,时间复杂度为O(n^2)。
本文介绍了一种用于单链表递归选择排序的Python程序,该程序实现简单,具有时间复杂度为O(n^2)的优点。通过本文的介绍,您可以了解程序的实现原理和使用方法,对于提高您的编程水平有一定的帮助。