用C语言实现单向链表的直接插入排序,冒泡排序和选择排序

求写程序
靠天靠地不如靠自己!
个人感觉链表的排序跟数组的排序在代码实现上差别还是挺大的,
把代码粘贴出来,以备后用。

算法思想到处都可以找到,程序代码还是得自己去写,自己亲手尝试过,才更理解其中的原理。
C和C++差别不大,算法是相同的。
加油吧!
温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-01-28
先别管是什么样的结构,这几个排序算法对于数组和链表没什么区别
排序无非就是改变element的顺序而已,数组改变两个下表的值
你链表改变下头尾指针,你觉得有什么区别?
第2个回答  推荐于2018-03-14
刚才我试了一下,样子是这样的,但具体细节上有问题,提供一个思路
时间问题没有调试通过,如果你觉得不行,当我没回答
#include<iostream>
using namespace std;

struct node
{
int value;
struct node *next;
};

struct link
{
struct node *head;
int length;
};

void show(struct node *head);

void selectsort(struct node*head);
void insertsort(struct node*head);
void bubblesort(struct node*head);

struct node* deletion(struct node*head, int n);
void insert(struct node*head, int n, struct node *q);

void main()
{
struct link *Link;
struct node *Node=Link->head=NULL;
Link->length=0;
for(int i=0;i<5;i++)
{
Node->value=i;
Node=Node->next;
}

insertsort(Link->head);
show(Link->head);
bubblesort(Link->head);
show(Link->head);
selectsort(Link->head);
show(Link->head);
}

void bubblesort(struct node*head)
{
struct node *p=head;
struct node *q=NULL;
struct node *s=head;
for(int j=1;s->next!=NULL;j++)
{
p=s;
for(int i=1;p->next!=NULL;i++)
{
if(p->next->value>p->value)
{
q=deletion(head,i);
insert(head, i-1, q);
}
p=p->next;
}
s=s->next;
}
}

void insertsort(struct node*head)
{
struct node *p=head;
struct node *q=NULL;
struct node *s=head->next;
for(int i=1;s!=NULL;i++)
{
int j=0;
while(p->next->value<s->next->value)
{
j++;
}
if(i!=j)
{
q=deletion(head, i);
insert(head, j, p);
}
s=s->next;
}
}

void selectsort(struct node *head)
{
struct node *p=head;
struct node *q=NULL;
struct node *s=head->next;
for(int i=0;s->next!=NULL;i++)
{
int max=s->value;
p=s->next;
for(int j=i+1;p!=NULL;j++)
{
if(p->value>s->value)
{
q=deletion(head, i);
insert(head, j, q);
}
p=p->next;
}
}
}

struct node*deletion(struct node *head, int n)
{
struct node *q=NULL;
struct node *p=head;
if(n==1)
{
q=head;
head=head->next;
}
else
{
int i=1;
while(i<n)
{
p=p->next;
}
q=p->next;
p->next=p->next->next;
}
return p;
}

void insert(struct node *head, int n, struct node *q)
{
struct node* p=head;
int i=1;
while(i<n)
{
p=p->next;
}
q->next=p->next;
p->next=q;
}

void show(struct node *head)
{
struct node *p=head;
while(p)
{
cout<<p->value<<endl;
p=p->next;
}
}本回答被提问者和网友采纳
第3个回答  2014-01-28
先把链表的基本操作实现;
把排序的算法搞懂;
搞不懂了多画画图,就会了
第4个回答  2014-01-28
数据结构中有啊

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网