基于单链表的简单选择排序
作者:
我是高情商
,
2024-07-24 22:14:04
,
所有人可见
,
阅读 1
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
struct Node {
int val;
Node* next;
Node(int x) : val(x), next(NULL) {}
};
Node* create_list(int arr[], int n) {
Node* head = NULL;
for (int i = 0; i < n; i++) {
Node* node = new Node(arr[i]);
if (head == NULL) {
head = node;
} else {
node->next = head;
head = node;
}
}
return head;
}
void print(Node* head) {
for (Node* p = head; p; p = p->next) {
cout << p->val << " ";
}
cout << endl;
}
void list_select_sort(Node* head) {
for (Node* cur = head; cur; cur = cur->next) {
Node* min = cur;
for (Node* q = cur->next; q; q = q->next) {
if (q->val < min->val) {
min = q;
}
}
swap(cur->val, min->val);
}
}
int main() {
int a[] = {1, 3, 5, 6, 8, 2, 1};
int n = sizeof(a) / sizeof(int);
Node* head = create_list(a, n);
list_select_sort(head);
print(head);
return 0;
}