快排算法的实现

单链表的快排

 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 }

猜你喜欢

转载自www.cnblogs.com/susidian/p/10013149.html