单链表的快速排序(转)
2010年11月30日 星期二 15:13
????? 單鏈表的快速排序和數(shù)組的快速排序在基本細(xì)想上是一致的,以從小到大來排序單鏈表為例,
都是選擇一個支點,然后把小于支點的元素放到左邊,把大于支點的元素放到右邊。
????? 但是,由于單鏈表不能像數(shù)組那樣隨機(jī)存儲,和數(shù)組的快排序相比較,還是有一些需要注意的細(xì)節(jié):
1. 支點的選取,由于不能隨機(jī)訪問第K個元素,因此每次選擇支點時可以取待排序那部分鏈表的頭指針。
2. 遍歷量表方式,由于不能從單鏈表的末尾向前遍歷,因此使用兩個指針分別向前向后遍歷的策略實效,
??? 事實上,可以可以采用一趟遍歷的方式將較小的元素放到單鏈表的左邊。具體方法為:
??? 1)定義兩個指針pslow, pfast,其中pslow指單鏈表頭結(jié)點,pfast指向單鏈表頭結(jié)點的下一個結(jié)點;
??? 2)使用pfast遍歷單鏈表,每遇到一個比支點小的元素,就和pslow進(jìn)行數(shù)據(jù)交換,然后令pslow=pslow->next。
3. 交換數(shù)據(jù)方式,直接交換鏈表數(shù)據(jù)指針指向的部分,不必交換鏈表節(jié)點本身。
?? 基于上述思想的單鏈表快排序?qū)崿F(xiàn)如下:
?#include <iostream>
#include <ctime>
using namespace std;
//單鏈表節(jié)點
struct SList
{
int data;
struct SList* next;
};
void bulid_slist(SList** phead, int n)
{
SList* ptr = NULL;
for(int i = 0; i < n; ++i)
{
?? SList* temp = new SList;
?? temp->data = rand() % n;
?? temp->next = NULL;
?? if(ptr == NULL)
?? {
??? *phead = temp;
??? ptr = temp;
?? }
?? else
?? {
??? ptr->next = temp;
??? ptr = ptr->next;
?? }
}
}
SList* get_last_slist(SList* phead)
{
SList* ptr = phead;
while(ptr->next)
{
?? ptr = ptr->next;
}
return ptr;
}
void print_slist(SList* phead)
{
SList* ptr = phead;
while(ptr)
{
?? printf("%d ", ptr->data);
?? ptr = ptr->next;
}
printf("\n");
}
void sort_slist(SList* phead, SList* pend)
{
if(phead == NULL || pend == NULL) return;
if(phead == pend) return;
SList* pslow = phead;
SList* pfast = phead->next;
SList* ptemp = phead;
while(pfast && pfast != pend->next)
{
?? if(pfast->data <= phead->data) //phead作為支點
?? {
??? ptemp = pslow;
??? pslow = pslow->next;
??? swap(pslow->data, pfast->data);
?? }
?? pfast = pfast->next;
}
swap(phead->data, pslow->data);
sort_slist(phead, ptemp);//ptemp為左右兩部分分割點的前一個節(jié)點
sort_slist(pslow->next, pend);
}
void destroy_slist(SList* phead)
{
SList* ptr = phead;
while(ptr)
{
?? SList* temp = ptr;
?? ptr = ptr->next;
?? delete temp;
}
}
int main(int argc, char** argv)
{
srand(time(NULL));
printf("sort single list\n");
SList* phead = NULL;
bulid_slist(&phead, 100);
print_slist(phead);
SList* plast = get_last_slist(phead);
printf("head:%d, last:%d\n", phead->data, plast->data);
sort_slist(phead, plast);
print_slist(phead);
destroy_slist(phead);
system("pause");
return 0;
}
轉(zhuǎn)自: ~純凈的天空~ 百度空間
轉(zhuǎn)載于:https://www.cnblogs.com/donlxn/archive/2011/09/24/2189496.html
總結(jié)
以上是生活随笔為你收集整理的单链表的快速排序(转)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [WCF 4.0新特性] 标准终结点与无
- 下一篇: 【转】经济计量学软件包Eviews快速使