隨手寫了個鏈表隨機化快速排序

 typedef LNode{dom

   int        data;ide

   LinkNode   *pNext; spa

}LinkNode,*pLinkList;it

 

LinkNode* LinkListPartition( LinkNode * const pHead, LinkNode * const pLeft, LinkNode * const pRight )io

{class

  Assert(NULL != pLeft && NULL != pRight);List

  LinkNode *pTraverse = pLeft;next

  int ListLength;tab

  while( pTraverse <= pRight )di

  {

    ListLength ++;

    pTraverse = pTraverse -> next;

  }

  

  // Radom pivot

  pTraverse = pLeft + random()%(ListLength); 

  

  LinkNode *pTemp = new  LinkNode;

  if( NULL != pTemp )

  {

  pTemp->data = pTraverse->data;

  }    

 

  // Save pivot

  swap(pTraverse, pLow);

  

  // Cursor

  LinkNode *pLow = pLeft;

  LinkNode *pHigh = pRight;

  

  while ( pLow < pHigh )

  {

    while( pLow < pHigh && pHigh->data <= pTemp->data )

    {

      ListLength--;

      pHigh = pLeft + ListLength;

    }

    

    pLow->data = pHigh->data;  

     

    while( pLow < pHigh && pLow->data >= pTemp->data)

    {

pLow = pLow->Next;      

    }

    

    pHigh->data = pLow->data;

  }

  pLow->data = pTemp->data;

  return pLow;

}

 

void QSortLinkNode( LinkNode * const pHead, LinkNode * const pLeft, LinkNode * const pRight )

{

  Assert(NULL != pHead);

  LinkNode *pivot = NULL;

  while(pLow->data < pHigh->data)

  {

    // One partition, twice recursion

    pivot = LinkListPartition( pHead, pLow, pHigh );

    QSortLinkNode( pHead, low, pivot-1 );

    QSortLinkNode( pHead, pivot+1, pHigh );    

  }  

}

相關文章
相關標籤/搜索