這部分實現的排序方法是冒泡排序和快速排序。
冒泡排序的基本思想就是對於給定的n個元素,從第一個元素開始,依次對相鄰的兩個元素進行比較,當前面的元素大於后面的元素時,交換其位置,進行一輪比較和換位后,n個元素中最大的數將位於第n位,然后對前(n-1)個元素進行第二輪比較,重復該過程,直到進行比較的元素只剩下一個。
單鏈表的快速排序和數組的快速排序在基本細想上是一致的,以從小到大來排序單鏈表為例,都是選擇一個支點,然后把小於支點的元素放到左邊,把大於支點的元素放到右邊。但是,由於單鏈表不能像數組那樣隨機存儲,和數組的快排序相比較,還是有一些需要注意的細節:
1. 支點的選取,由於不能隨機訪問第K個元素,因此每次選擇支點時可以取待排序那部分鏈表的頭指針。
2. 遍歷鏈表方式,由於不能從單鏈表的末尾向前遍歷,因此使用兩個指針分別向前向后遍歷的策略實效,可以可以采用一趟遍歷的方式將較小的元素放到單鏈表的左邊。具體方法為:
1)定義兩個指針pSlow, pFast,其中pSlow指單鏈表頭結點,pFast指向單鏈表頭結點的下一個結點;
2)使用pFast遍歷單鏈表,每遇到一個比支點小的元素,就和pSlow進行數據交換,然后令pSlow=pSlow->next。
3. 交換數據方式,直接交換鏈表數據指針指向的部分,不必交換鏈表節點本身。
快排這里還是寫了兩個函數,Partition這個函數,返回的支點結點的前一個位置。
#include <iostream> #include <algorithm> #include "string.h" #include "stdio.h" #include <vector> #include <deque> #include<stack> using namespace std; struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class List{ public: ListNode* CreatList(int* arr,int len) { int val; ListNode* pHead = new ListNode(arr[0]); ListNode* pCurrent=NULL; ListNode* rear = pHead; int count = 1; while(count<len) { ListNode* pCurrent = new ListNode(arr[count]); rear->next = pCurrent; rear = pCurrent; count++; } rear->next = NULL; return pHead; } void ShowList(ListNode* pHead) { while(pHead) { cout<<pHead->val<<" "; pHead = pHead->next; } cout<<endl; } //得到鏈表中最后一個結點
ListNode* GetLastNode(ListNode* pHead) { ListNode* pNode = pHead; while(pNode->next!=NULL) { pNode=pNode->next; } return pNode; } }; class Sort{ public: //冒泡排序
ListNode* BubbleSortList(ListNode* pHead) { ListNode* pNode1 = pHead; ListNode* pNode2 = pHead; if(pHead == NULL) return NULL; for(;pNode1->next!=NULL;pNode1=pNode1->next) { for(pNode2=pHead;pNode2->next!=NULL;pNode2=pNode2->next) { if(pNode2->val>pNode2->next->val) { int temp = pNode2->val; pNode2->val = pNode2->next->val; pNode2->next->val = temp; } } } return pHead; } //快速排序
void QuickSortList(ListNode* pHead,ListNode* pEnd) { if(pHead != pEnd) { ListNode* part = Partition(pHead,pEnd); QuickSortList(pHead,part); QuickSortList(part->next,pEnd); } } ListNode* Partition(ListNode* pBegin,ListNode* pEnd) { int key = pBegin->val; ListNode* pSlow = pBegin; ListNode* pFast = pSlow->next; ListNode* temp = pBegin; while(pFast!=NULL&&pFast!=pEnd->next) { if(pFast->val <key) { temp = pSlow;
pSlow = pSlow->next; swap(pSlow->val,pFast->val); } pFast = pFast->next; } swap(pSlow->val,pBegin->val); return temp;//返回的結點為支點節點的前一個結點
} }; int main() { int array[]={3,4,5,1,2,8,7}; List list; Sort sort; ListNode* pHead1 = list.CreatList(array,sizeof(array)/sizeof(array[0])); ListNode* pHead2 = list.CreatList(array,sizeof(array)/sizeof(array[0])); list.ShowList(pHead1); sort.BubbleSortList(pHead1); list.ShowList(pHead1); ListNode* pEnd = list.GetLastNode(pHead2); //cout<<pEnd->val<<endl; sort.QuickSortList(pHead2,pEnd); list.ShowList(pHead2); return 0; }
