用C语言编写一个以单链表为存储结构实现简单选择排序的算法
时间: 2024-02-15 15:02:21 浏览: 97
好的,以下是使用单链表实现简单选择排序的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
void swap(Node *p, Node *q) {
int temp = p->data;
p->data = q->data;
q->data = temp;
}
void selection_sort(Node *head) {
Node *p = head->next;
while (p != NULL) {
Node *min = p;
Node *q = p->next;
while (q != NULL) {
if (q->data < min->data) {
min = q;
}
q = q->next;
}
if (min != p) {
swap(min, p);
}
p = p->next;
}
}
void print_list(Node *head) {
Node *p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
Node *head = (Node*)malloc(sizeof(Node));
head->next = NULL;
int n, x;
printf("Enter the number of elements: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("Enter element %d: ", i + 1);
scanf("%d", &x);
Node *new_node = (Node*)malloc(sizeof(Node));
new_node->data = x;
new_node->next = head->next;
head->next = new_node;
}
printf("Before sorting: ");
print_list(head);
selection_sort(head);
printf("After sorting: ");
print_list(head);
return 0;
}
```
这个程序首先要求用户输入链表中元素的数量和值,然后使用单链表存储这些元素。接着,它调用 `selection_sort` 函数对链表进行排序,并使用 `print_list` 函数输出排序后的链表。
阅读全文