设待排序的表有10个元素,其关键字分别为(9,8,7,6,5,4,3,2,1,0),实现冒泡排序算法,用以上数据进行测试病输出各趟的排序结果。
运行结果要求直接能在控制台输出,使用c++编写。
线性表冒泡排序代码如下:
代码:
#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct _data
{
ElemType data;
struct _data* next;
}LinkNode, * LinkList;
//显示链表
void showList(LinkList head)
{
LinkList p = head->next;
while (p)
{
cout << p->data<<" ";
p = p->next;
}
cout << endl;
}
//冒泡排序
void bubble_sort(LinkNode* L)
{
LinkNode* p, * tail, * q;
int tms = 1;
tail = NULL;
while ((L->next->next) != tail)
{
p = L;
q = L->next;
while (q->next != tail)
{
if (q->data > q->next->data) //升序排列
{
p->next = q->next;
q->next = q->next->next;
p->next->next = q;
q = p->next;
}
q = q->next;
p = p->next;
}
cout << "第" << tms << "遍排序结果:";
tms++;
showList(L); //显示链表
tail = q;
}
}
int main()
{
ElemType a[] = { 9,8,7,6,5,4,3,2,1,0 };
LinkList head, p, t, maxnode, prenode;
int len = sizeof(a) / sizeof(int); //得到数组的大小
int i;
head = (LinkList)malloc(sizeof(LinkNode)); //创建头节点
head->next = 0;
p = head;
//用数组元素构建链表
for (i = 0; i < len; i++)
{
t = (LinkList)malloc(sizeof(LinkNode));
t->next = 0;
t->data = a[i];
//节点插入链表
p->next = t;
p = t;
}
//链表排序
bubble_sort(head);
//遍历排序后的链表
cout << "最终结果:";
showList(head);
return 0;
}
你题目的解答代码如下:
#include<iostream>
using namespace std;
void sort(int a[],int n)
{
int i,j;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j] > a[j+1])
{
int t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
cout << "第" << i+1 << "趟的排序结果: ";
for (j = 0; j < n; j++)
cout << a[j] << " ";
cout << endl;
}
}
int main()
{
int i,n;
int a[] = {9,8,7,6,5,4,3,2,1,0};
sort(a,10);
cout << "最终排序结果" << endl;
for (i = 0; i < 10; i++)
cout << a[i] << " ";
return 0;
}
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!