c语言单项链表排序之基于冒泡排序实现

typedef struct link_t {
int data;
struct link_t* next;
}link_t;
link_t* push_back_link(link_t* head, int value) {
link_t* node = (link_t*)malloc(sizeof(link_t));
node->data = value;
node->next = NULL;
if (head == NULL) {
head = node;
}
else {
link_t* temp = head;
while (temp->next) {
temp = temp->next;
}
temp->next = node;
}
return head;
}
void print_link(link_t* head) {
link_t* temp = head;
while (temp)
{
printf("value:%d\r\n", temp->data);
temp = temp->next;
}
}
void free_link(link_t* head) {
link_t* temp = head;
while (temp)
{
link_t* next = temp->next;
free(temp);
temp = next;
}
}
void sort_link(link_t* link) {
link_t* head = link;
if (head == NULL || head->next == NULL)
return;
link_t* next = link->next;
while (1) {
bool flag = false;
while (next) {
int value = head->data;
if (next->data < head->data) {
head->data = next->data;
next->data = value;
flag = true;
}
head = head->next;
next = next->next;
}
head = link;
next = link->next;
if (!flag) {
break;
}
}
}
测试:
void test_link() {
link_t* head = NULL;
head = push_back_link(head, 10);
head = push_back_link(head, 2);
head = push_back_link(head, 3);
head = push_back_link(head, 3);
head = push_back_link(head, 1);
head = push_back_link(head, 3);
head = push_back_link(head, 0);
/* head = push_front_link(head, 4);
head = push_front_link(head, 5);
head = push_front_link(head, 6);*/
print_link(head);
cout << "-----------------" << endl;
//delete_link(head, 0);
//head = delete_link(head, 0);
sort_link(head);
print_link(head);
free_link(head);
}
附冒泡排序:
int arr[] = { 3,6,1 };
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2-i; j++) {
int temp = arr[j];
if (arr[j + 1] < arr[j]) {
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int i = 0; i < 3; i++) {
cout << arr[i] << endl;
}

浙公网安备 33010602011771号