以文本方式查看主题

-  中文XML论坛 - 专业的XML技术讨论区  (http://bbs.xml.org.cn/index.asp)
--  『 计算机考研交流 』   (http://bbs.xml.org.cn/list.asp?boardid=67)
----  [讨论]快速排序算法  (http://bbs.xml.org.cn/dispbbs.asp?boardid=67&rootid=&id=38205)


--  作者:hongjunli
--  发布时间:9/22/2006 4:05:00 PM

--  [讨论]快速排序算法
若待排序列用单链表表示(不带头接点)试给出起快速排序算法(要求以首元接点的数据域的关键字值为轴元素,先用文字写出实现的基本思想,再用c语言写出算法)


大家老讨论一下,看看这个算法如何实现啊,如果用双链表的话,比较好实现,但是现在是要求单链表来实现,大家来讨论一下,看看用单链表如何来实现这个算法啊?


--  作者:Logician
--  发布时间:9/22/2006 5:20:00 PM

--  
似乎比较简单啊。
只要逐一把首节点的关键字与之后节点的关键字比较,小的串在一个链表里,大的串在另一个链表里,最后把首节点接在小链表的末尾,大链表接后面就可以了。
--  作者:Logician
--  发布时间:9/22/2006 5:58:00 PM

--  
#include <iostream>
#include <time.h>
using namespace std;

template <class KeyType, class DataType>
class SLNode
{
public:
 KeyType key;
 DataType data;
 SLNode<KeyType,DataType> *next;
};

template <class KeyType, class DataType>
SLNode<KeyType,DataType> *QuickSort(SLNode<KeyType,DataType> *first)
{
 KeyType firstKey;
 SLNode<KeyType,DataType> *small_first, *small_last, *big_first, *big_last, *cur;
 if(first==NULL)
  return NULL;
 else
 {
  small_first=NULL;
  big_first=NULL;
  small_last=NULL;
  big_last=NULL;
  firstKey=first->key;
  for(cur=first->next;cur!=NULL;cur=cur->next)
  {
   if(cur->key<firstKey)
   {
    if(small_first==NULL)
    {
     small_first=cur;
     small_last=cur;
    }
    else
    {
     small_last->next=cur;
     small_last=cur;
    }
   }
   else
   {
    if(big_first==NULL)
    {
     big_first=cur;
     big_last=cur;
    }
    else
    {
     big_last->next=cur;
     big_last=cur;
    }

   }
  }
  if(small_last!=NULL)
   small_last->next=NULL;
  if(big_last!=NULL)
   big_last->next=NULL;
  small_first = QuickSort(small_first);
  big_first = QuickSort(big_first);
  first->next=big_first;
  if(small_first!=NULL)
  {
   for(cur=small_first;cur->next!=NULL;cur=cur->next);
   cur->next=first;
   first=small_first;
  }
  return first;
 }
}

void main()
{
 int i;
 SLNode<int,int> *first, *last, *p;
 srand((unsigned)time( NULL ));
 first=NULL;
 for(i=1;i<=100;i++)
 {
  p=new SLNode<int,int>;
  p->data=i;
  p->key=rand();
  if(first==NULL)
  {
   first=p;
   last=p;
  }
  else
  {
   last->next=p;
   last=p;
  }
 }
 last->next=NULL;
 for(p=first;p!=NULL;p=p->next)
  cout<<p->key<<","<<p->data<<"; ";
 cout<<endl<<endl;
 first = QuickSort(first);
 for(p=first;p!=NULL;p=p->next)
  cout<<p->key<<","<<p->data<<"; ";
 cout<<endl;
}


--  作者:Supremgoooo
--  发布时间:9/22/2006 11:09:00 PM

--  
对!
W 3 C h i n a ( since 2003 ) 旗 下 站 点
苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》
78.125ms