单向链表的简单选择排序

作业

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是单向链表的快速排序的C语言实现: ```c #include <stdio.h> #include <stdlib.h> // 定义链表结构体 typedef struct Node { int value; struct Node* next; } Node; // 创建链表节点 Node* createNode(int value) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->value = value; newNode->next = NULL; return newNode; } // 将链表拆分成小于和大于pivot的两个链表 void partition(Node* head, int pivot, Node** lessHead, Node** greaterHead) { Node* lessTail = NULL; Node* greaterTail = NULL; Node* curr = head; while (curr != NULL) { Node* next = curr->next; if (curr->value < pivot) { if (*lessHead == NULL) { *lessHead = curr; lessTail = curr; lessTail->next = NULL; } else { lessTail->next = curr; lessTail = curr; lessTail->next = NULL; } } else { if (*greaterHead == NULL) { *greaterHead = curr; greaterTail = curr; greaterTail->next = NULL; } else { greaterTail->next = curr; greaterTail = curr; greaterTail->next = NULL; } } curr = next; } } // 快速排序 Node* quickSort(Node* head) { if (head == NULL || head->next == NULL) { return head; } Node* lessHead = NULL; Node* greaterHead = NULL; // 将链表拆分成小于和大于pivot的两个链表 partition(head->next, head->value, &lessHead, &greaterHead); // 递归快排小于和大于pivot的两个链表 lessHead = quickSort(lessHead); greaterHead = quickSort(greaterHead); // 将小于pivot的链表和大于pivot的链表连接起来 head->next = greaterHead; if (lessHead == NULL) { return head; } Node* curr = lessHead; while (curr->next != NULL) { curr = curr->next; } curr->next = head; return lessHead; } // 打印链表 void printList(Node* head) { while (head != NULL) { printf("%d ", head->value); head = head->next; } printf("\n"); } int main() { Node* head = createNode(5); head->next = createNode(3); head->next->next = createNode(8); head->next->next->next = createNode(4); head->next->next->next->next = createNode(2); printf("Before sorting: "); printList(head); head = quickSort(head); printf("After sorting: "); printList(head); return 0; } ``` 输出: ``` Before sorting: 5 3 8 4 2 After sorting: 2 3 4 5 8 ``` 这里的快速排序算法的时间复杂度是O(nlogn),空间复杂度是O(1),其中n是链表的长度。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值