#include<iostream>
using namespace std;
struct node{
float num;
node* next;
};
class numlist
{
public:
numlist();
~numlist();
void print();
void sort();
private:
node* h;
};
numlist::numlist()
{
h=0;
float num;
node *cur;
cout<<"Create the list and input the number by order.To end input -1."<<endl;
cin>>num;
while(num!=-1)
{
if(!h)
{
h=new node;
cur=h;
h->num=num;
h->next=0;
}
else
{
cur->next=new node;
cur=cur->next;
cur->num=num;
}
cin>>num;
}
if(h)
cur->next=0;
}
numlist::~numlist()
{
node *cur=h;
while(h)
{
h=h->next;
delete cur;
cur=h;
}
}
void numlist::print()
{
node *cur=h;
if(!cur)
cerr<<"error when printing because the list is empty"<<endl;
while(cur)
{
cout<<cur->num<<" ";
cur=cur->next;
}
}
void numlist::sort()
{
if(!h)
{
cerr<<"error when sorting because the list is empty"<<endl;
exit(1);
}
node *p1,*p2,*p3,*p4;
p1=h;
h=h->next;
p1->next=0;
while(h)
{
p2=h->next;
if(h->num<p1->num)
{
h->next=p1;
p1=h;
h=p2;
}
else
{
p3=p1;
p4=p3->next;
while(h->num>p3->num && p4)
{
p3=p4;
p4=p4->next;
}
if(!p4)
{
h->next=0;
p3->next=h;
h=p2;
}
else
{
p3->next=h;
h->next=p4;
h=p2;
}
}
}
h=p1;
}
int main()
{
numlist a;
a.print();
a.sort();
cout<<endl;
a.print();
return 0;
}
这是完整的程序...
下面换一下sort 函数
void numlist::sort()
{
if(!h)
{
cerr<<"error when sorting because the list is empty"<<endl;
exit(1);
}
node* p1,*p2,*p3,*p4;
p2=h;
p1=h->next;
if(!p1)
return;
else
{
while(p1)
{
while(p2->num<p1->num)
{
p2=p1;
p1=p1->next;
}//end while
if(p1->num<h->num)
{
p2->next=p1->next;
p1->next=h;
h=p1;
p1=p2->next;
}//end if
else
{
p3=h;
p4=h->next;
while(p4->num<p1->num)
{
p3=p4;
p4=p4->next;
}
if(p4!=p1)
{
p3->next=p1;
p2->next=p1->next;
p1->next=p4;
p1=p2->next;
}
else
{
p2=p1;
p1=p1->next;
}
}//end else
}//end while
}
}
想问一下这两个sort的区别...哪个函数效率比较高...