C++中的快排

算法的思想,将要排序的链表分成两部分A和B,A中初始放入链表中的第一个元素,B为链表中的剩余元素。将B中的元素一次插入A中,并排好顺序,直到B中元素为空。

代码奉上= =、

#include <iostream>
using namespace std;
struct Node{
int element;
Node *next;
};
Node *h = NULL;
struct ANode{
int element;
ANode *next;
};
ANode *head = NULL;
bool insert(int a,Node *&h){
int click = 0;
Node *p ;
p = new Node;
p->element = a;
if (h ==NULL)
{
h = p;
p->next = NULL;
click = 1;
}else{
Node *qn ;
qn = h;
while (qn->next!=NULL)
{
qn = qn->next;
}
qn->next = p;
p->next = NULL;
click = 1;
}
if (click ==0)
{
return false;
}else
return true;
}


ANode *sort(Node *&h){
Node *q = h;
ANode *p;
p = new ANode;
p->element = q->element;
head = p;
h = h->next;
p->next = NULL;
delete q;
while (h!=NULL)
{
Node *q = h;
ANode *p,*p1 = head,*p2 = head;
p = new ANode;
p->element = q->element;
while ((p->element>p1->element)&&(p1->next!=NULL))
{
p2 = p1;
p1 = p1->next;
}
if (p->element<p1->element)
{
if (p1==head)
{
head = p;
p->next = p1;
h = h->next;
delete q;
}else{
p2->next = p;
p->next = p1;
h = h->next;
   delete q;
}
}
else if (p->element ==p1->element)
{
if (p1==head)
{
head = p;
p->next = p1;
h = h->next;
delete q;
}else{
p2->next = p;
p->next = p1;
h = h->next;
delete q;
}
}
else if (p1->next ==NULL)
{
p1->next = p;
p->next = NULL;
h = h->next;
delete q;
}
}
return head;
}
void main(){
int a;
bool t;
int i=0;
while(true)
{
char ch;
cout<<"请输入要插入的数值:";
cin>>a;
t=insert(a,h);
if(t)
cout<<"插入成功"<<endl;
else
cout<<"插入失败"<<endl;
cout<<"要继续插入吗?(y/n)";
cin>>ch;
if(ch=='N'||ch=='n')
break;//break的作用是退出包含它的最内层循环
}
Node *q=h;
cout<<"链表的元素依次为:"<<endl;
while(q->next!=NULL)
{
cout<<q->element<<' ';
q=q->next;
}
cout<<q->element<<endl;
head=sort(h);
ANode *q1=head;
cout<<"排序后的链表元素依次为:"<<endl;
while(q1->next!=NULL)
{
cout<<q1->element<<' ';
q1=q1->next;
}
cout<<q1->element<<endl;
}

感觉这个代码主要是要理清楚算法。

然后想到了程序=数据结构+算法这句话的真谛、

晚安晚安,碎告碎告咯

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值