日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

单链表的快速排序(转)

發布時間:2024/8/22 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 单链表的快速排序(转) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

2010年11月30日 星期二 15:13

????? 單鏈表的快速排序和數組的快速排序在基本細想上是一致的,以從小到大來排序單鏈表為例,

都是選擇一個支點,然后把小于支點的元素放到左邊,把大于支點的元素放到右邊。

????? 但是,由于單鏈表不能像數組那樣隨機存儲,和數組的快排序相比較,還是有一些需要注意的細節:

1. 支點的選取,由于不能隨機訪問第K個元素,因此每次選擇支點時可以取待排序那部分鏈表的頭指針。

2. 遍歷量表方式,由于不能從單鏈表的末尾向前遍歷,因此使用兩個指針分別向前向后遍歷的策略實效,

??? 事實上,可以可以采用一趟遍歷的方式將較小的元素放到單鏈表的左邊。具體方法為:

??? 1)定義兩個指針pslow, pfast,其中pslow指單鏈表頭結點,pfast指向單鏈表頭結點的下一個結點;

??? 2)使用pfast遍歷單鏈表,每遇到一個比支點小的元素,就和pslow進行數據交換,然后令pslow=pslow->next。

3. 交換數據方式,直接交換鏈表數據指針指向的部分,不必交換鏈表節點本身。

?? 基于上述思想的單鏈表快排序實現如下:

?#include <iostream>
#include <ctime>
using namespace std;
//單鏈表節點

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為左右兩部分分割點的前一個節點
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;
}

轉自: ~純凈的天空~ 百度空間

轉載于:https://www.cnblogs.com/donlxn/archive/2011/09/24/2189496.html

總結

以上是生活随笔為你收集整理的单链表的快速排序(转)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。