现有n个随机整形数,以链表的方式链式存储,使用基数排序法对其排序。因为所有数据在计算机内都是二进制存储,只有0,1两种数字,因此要求,仅使用两个“桶”来做基数排序,即一个桶代表0,一个桶代表1。写出算法思想,并用C语言进行编程
时间: 2023-09-28 14:03:45 浏览: 128
所有基础数据结构和算法的纯C语言实现,如各自排序、链表、栈、队列、各种树....
算法思想:
1. 定义两个桶,一个桶用来存储0,一个桶用来存储1。
2. 从最低位开始,对每个数字进行判断,如果该位为0,则将其放入0桶中,如果该位为1,则将其放入1桶中。
3. 将0桶中的数按顺序连接起来,再将1桶中的数按顺序连接起来,得到一个新的链表。
4. 对新链表重复步骤2和3,直到最高位。
5. 排序完成。
C 语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
void radixSort(struct ListNode **lst) {
if (*lst == NULL || (*lst)->next == NULL) {
return;
}
struct ListNode *zeroBucket = NULL, *oneBucket = NULL;
int i, maxVal = 0, exp = 1;
struct ListNode *cur = *lst;
while (cur != NULL) {
if (cur->val > maxVal) {
maxVal = cur->val;
}
cur = cur->next;
}
while (maxVal / exp > 0) {
struct ListNode *cur = *lst, *curZero = NULL, *curOne = NULL;
while (cur != NULL) {
if ((cur->val / exp) % 2 == 0) {
if (curZero == NULL) {
curZero = cur;
zeroBucket = cur;
} else {
curZero->next = cur;
curZero = curZero->next;
}
} else {
if (curOne == NULL) {
curOne = cur;
oneBucket = cur;
} else {
curOne->next = cur;
curOne = curOne->next;
}
}
cur = cur->next;
}
if (curZero != NULL) {
curZero->next = NULL;
}
if (curOne != NULL) {
curOne->next = NULL;
}
if (zeroBucket != NULL) {
*lst = zeroBucket;
}
while (zeroBucket != NULL && zeroBucket->next != NULL) {
zeroBucket = zeroBucket->next;
}
if (oneBucket != NULL) {
zeroBucket->next = oneBucket;
}
while (oneBucket != NULL && oneBucket->next != NULL) {
oneBucket = oneBucket->next;
}
exp *= 2;
}
}
void printList(struct ListNode *lst) {
while (lst != NULL) {
printf("%d ", lst->val);
lst = lst->next;
}
printf("\n");
}
int main() {
struct ListNode *lst = (struct ListNode *)malloc(sizeof(struct ListNode));
lst->val = 1;
lst->next = (struct ListNode *)malloc(sizeof(struct ListNode));
lst->next->val = 3;
lst->next->next = (struct ListNode *)malloc(sizeof(struct ListNode));
lst->next->next->val = 2;
lst->next->next->next = (struct ListNode *)malloc(sizeof(struct ListNode));
lst->next->next->next->val = 5;
lst->next->next->next->next = (struct ListNode *)malloc(sizeof(struct ListNode));
lst->next->next->next->next->val = 4;
lst->next->next->next->next->next = NULL;
printf("Before sorting: ");
printList(lst);
radixSort(&lst);
printf("After sorting: ");
printList(lst);
return 0;
}
```
阅读全文