用C语言数据结构二叉树编写程序实现直接插入排序算法
时间: 2023-10-22 19:06:30 浏览: 46
抱歉,之前的回答有误,二叉树和直接插入排序算法没有必然的联系,不能用二叉树来实现直接插入排序。下面是使用链表实现直接插入排序的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
void insert(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else if ((*head)->data >= value) {
newNode->next = *head;
*head = newNode;
} else {
Node* current = *head;
while (current->next != NULL && current->next->data < value) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
void insertionSort(Node** head) {
Node* sortedList = NULL;
Node* current = *head;
while (current != NULL) {
Node* next = current->next;
insert(&sortedList, current->data);
current = next;
}
*head = sortedList;
}
void printList(Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
Node* head = NULL;
insert(&head, 12);
insert(&head, 11);
insert(&head, 13);
insert(&head, 5);
insert(&head, 6);
printf("Before sorting: ");
printList(head);
insertionSort(&head);
printf("After sorting: ");
printList(head);
return 0;
}
```
在这个示例中,我们使用链表来实现直接插入排序算法。我们定义了 `Node` 结构体来表示链表节点,并实现了 `insert` 函数来将新节点插入到已排序的链表中。`insertionSort` 函数遍历未排序的链表,并将每个节点插入到已排序的链表中。最后,我们使用 `printList` 函数来打印已排序的链表。
希望这个示例能够帮助你理解如何使用链表实现直接插入排序算法。