双向冒泡排序
#include<iostream> using namespace std; typedef struct node { int data; struct node *prior, *next; }node, *LinkList; void Sort(LinkList &L) { int exchange = 1; LinkList head = L; LinkList tail = NULL; while (exchange) { LinkList p = head->next; exchange = 0; while (p->next!= tail) { if (p->data > p->next->data) { LinkList temp = p->next; exchange = 1; p->next = temp->next; if (temp->next)temp->next->prior = p; temp->next = p; p->prior->next = temp; temp->prior = p->prior; p->prior = temp; } else p = p->next; } tail = p; p = tail->prior; while (exchange&&p->prior != head) { if (p->data < p->prior->data) { /*LinkList temp = p->prior; exchange = 1; p->prior = temp->prior; temp->prior->next = p; temp->prior = p; p->next->prior = temp; temp->next = p->next; p->next = temp;*/ int temp;//直接交换数值 temp = p->prior->data; p->prior->data = p->data; p->data = temp; exchange = 1; } p = p->prior;//直接交换数值要往后移动指针 } head = p; } } void Create(LinkList &L, int n) { LinkList p, rear; L = new node; L->next = NULL; L->prior = NULL; rear = L; while (n--) { p = new node; cin >> p->data; p->next = rear->next; rear->next = p; p->prior = rear; rear = p; } } void Print(LinkList &L) { LinkList p = L->next; while (p->next) { cout << p->data << " "; p = p->next; } cout << p->data << endl; } int main() { int n; while (true) { cin >> n; if (!n)break; else { LinkList L; Create(L, n); Sort(L); Print(L); } } return 0; }
基于双向链表的双向冒泡排序法
描述
有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