1. 程式人生 > >快排演算法的實現

快排演算法的實現

單鏈表的快排

 1 void QuickSort(struct Node *head,struct Node *tail)
 2 {
 3 if(head == NULL)
 4 return ;
 5 if(head == tail )
 6 return ;
 7 int pivot = head->data;
 8 struct Node *p = head;
 9 struct Node *q = p->next;
10 while(q != tail)
11 {
12 if(q->data<pivot) //每次都選擇待排序連結串列的頭結點作為劃分的基準
13
{ 14 p = p->next; 15 int tmp = p->data; //p指標指向比基準小的節點組成的連結串列 16 p->data = q->data; 17 q->data =tmp; 18 } 19 q=q->next; 20 } 21 int tmp = p->data; 22 p->data = head->data; 23 head->data =tmp; 24 QuickSort(head,p); //比基準元素小的連結串列 25 QuickSort(p->next,NULL); //右邊是比基準大的節點組成的連結串列
26 }

快排的非遞迴實現

 1 int Partition(int *a,int low,int high)
 2 {
 3 while(low<high)
 4 {
 5 while(low<high && a[high] >= a[low])
 6 --high;
 7 swap(a[low],a[high]);
 8 while(low<high && a[low] <= a[high])
 9 ++low;
10 swap(a[low],a[high]);
11 }
12 return low;
13 }
14
15 16 void quickSort(int *a,int low ,int high) { 17 if(a== NULL || low< 0 || high <0) 18 return ; 19 stack<int> s; 20 if(low<high) 21 { 22 int pivot = Partition(a,low,high); 23 if(low < pivot -1) 24 { 25 s.push(low); 26 s.push(pivot-1); 27 } 28 if(pivot+1 < high) 29 { 30 s.push(pivot+1); 31 s.push(high); 32 } 33 while(!s.empty()) 34 { 35 int start = s.top(); 36 s.pop(); 37 int end = s.top(); 38 s.pop(); 39 pivot = Partition(a,start,end); 40 if(start < pivot -1 ) 41 { 42 s.push(start); 43 s.push(pivot-1); 44 } 45 if(pivot+1 < end) 46 { 47 s.push(pivot+1); 48 s.push(end); 49 } 50 } 51 } 52 }