C++中的快排

来源:互联网 发布:姿态融合算法 编辑:程序博客网 时间:2024/06/04 18:54

算法的思想,将要排序的链表分成两部分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;
}

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

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

晚安晚安,碎告碎告咯