以单链表实现简单选择排序
时间: 2023-07-20 13:45:21 浏览: 110
好的,下面是以单链表实现简单选择排序的代码:
```python
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def selection_sort(head):
if head is None:
return None
current = head
while current.next is not None:
min_node = current
iterator = current.next
while iterator is not None:
if iterator.data < min_node.data:
min_node = iterator
iterator = iterator.next
if current != min_node:
current.data, min_node.data = min_node.data, current.data
current = current.next
return head
```
该算法的思路是在列表中找到最小的元素并将其放到列表的最前面,接着再从剩余未排序的元素中找到最小的元素放到已排序的末尾,以此类推,直到整个列表都有序。
这里的数据结构是单链表,每个节点有一个 data 属性和 next 属性,其中 next 属性用于指向下一个节点。selection_sort 函数接受一个链表头节点 head,返回排序后的链表头节点。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)