基于双向链表的双向冒泡排序法
描述
有n个记录存储在带头结点的双向链表中,利用双向冒泡排序法对其按上升序进行排序,请写出这种排序的算法。(注:双向冒泡排序即相邻两趟排序向相反方向冒泡)。
输入
多组数据,每组数据两行。第一行为序列的长度n,第二行为序列的n个元素(元素之间用空格分隔,元素都为正整数)。当n等于0时,输入结束。
输出
每组数据输出一行,为从小到大排序后的序列。每两个元素之间用空格隔开。
输入样例 1
5 4 5 3 2 9 6 1 3 5 7 9 2 0
输出样例 1
2 3 4 5 9 1 2 3 5 7 9
#include<iostream>
using namespace std;
typedef struct LNode {
int data;
struct LNode* next, * front;
}LNode,*LinkList;
void Create(LinkList& L, int n) {
L = new LNode;
L->next = NULL;
L->front = NULL;
LNode* s, * r = L;
for (int i = 0; i < n; i++) {
s = new LNode;
cin >> s->data;
s->next = r->next;
s->front = r;
r->next = s;
r = s;
}
}
void Sort(LinkList &L) {
LNode* head = L;
LNode* tail = NULL;
int flag = 1;
while (flag) {//向下冒泡
LNode* p = head->next;//工作指针
flag = 0;//提前结束
while (p->next!=tail) {
if (p->data > p->next->data) {//冒泡交换
flag = 1;
LNode* temp = p->next;
p->next = temp->next;
if (temp->next != NULL) { temp->next->front = p; }
p->front->next = temp;
temp->front = p->front;
p->front = temp;
temp->next = p;
}
else {
p = p->next;
}
}
tail = p;
p = tail->front;
while (flag && p->front != head) {
if (p->data < p->front->data) {
LNode* temp = p->front;
p->front = temp->front;
if (temp->front != NULL) { temp->front->next = p; }
p->next->front = temp;
temp->next = p->next;
temp->front = p;
p->next = temp;
}
else {
p = p->front;
}
}
head = p;
}
}
void Output(LinkList L) {
LNode* p = L->next;
while (p) {
if (p->next != NULL) {
cout << p->data << " ";
}
else {
cout << p->data;
}
p = p->next;
}
cout << endl;
}
int main() {
int n;
while (cin >> n && n != 0) {
LinkList L1;
Create(L1, n);
Sort(L1);
Output(L1);
}
}