3.序列劃分演算法
輸入:序列A[p...r].
存在下標q(p<=q<=r),其中A[p...q]中的元素不超過A[r],而A[q+1...r]中的元素均大於A[r].
設定兩個下標i,j初始時分別為p-1和p.讓j在[p...r]中掃描,若A[j]<=A[r],則將A[j]與A[i+1]交換,然後i增加1.隨著j的增加,A[p...i]和A[i+1...j]也會增長,最終j到達r,將A[i+1]與A[r]交換。
演算法虛擬碼:
1. x<-A[r]
2. i<-p-1
3. for j<-p to r-1
4. do if A[j]<=x
5. then i<-i+1
6. exchange A[i]<->A[j]
7. exchange A[i+1]<->A[r]
8. return i+1
C++:
#include<iostream>
#include<iterator>
#include<vector>
#include<list>
#include<algorithm>
#include<functional>
using namespace std;
int main(){
int a[]={1,2,5,8,9,0,3,4,6,7},i;
string b[]={"AoMen","BeiJing","ShangHai","ChongQing","TianJin","XiangGang"};
double c[]={0.5,3.7,6.3,8.5,9.2,1.7,2.3,4.1,5.9,7.4};
vector vb=vector(b,b+6);
list lc=list(c,c+10);
i=distance(a,stable_partition(a,a+10,bind2nd(greater_equal(),a[9])));//其中greater是大於,這裡數值類的都用greater_equal
//其中的stable_partition是一個STL中的模板函式,意思就是按照第三個引數的規則,將a,a+10內的資料進行劃分為[a,a+middle],[a+middle,a+10],並返回middle的下標
//bind2nd(greater_equal(),a[9])是一個定義在functional中的仿函式,意思就是確定劃分的標準—按末尾元素a[9]進行劃分,前半段部分大於該值greater_equal(),後半段小於該值
copy(a,a+10,ostream_iterator(cout," "));
cout<<endl<<i<<endl;
i=distance(vb.begin(),stable_partition(vb.begin(),vb.end(),bind2nd(less_equal(),*--vb.end())));//less表示小於
copy(vb.begin(),vb.end(),ostream_iterator(cout," "));
cout<<endl<<i<<endl;
i=distance(lc.begin(),stable_partition(lc.begin(),lc.end(),bind2nd(greater_equal(),*--lc.end())));
copy(lc.begin(),lc.end(),ostream_iterator(cout," "));
cout<<endl<<i<<endl;
}
JAVA:
LinearList.java
package test;
import java.util.*;
public class LinearList {
public static int partition(List a,int p,int r,Comparator comp)//如果要對集合物件或陣列物件進行排序,需要實現Comparator介面以達到我們想要的目標。
{
Comparable x;
int i,j;
x=a.get(r);
i=p-1;
for(j=p;j<r;j++)
if(comp.compare(a.get(j), x)<=0) {//如果不符合規則比較則為-1,符合則為1
i++;
Collections.swap(a, i, j);
}
Collections.swap(a, i+1, r);
return i+1;
}
}
Greater.java
package test;
import java.util.Comparator;
public class Greater implements Comparator{
public int compare(Comparable x,Comparable y) {
return x.compareTo(y);
}
}
Less.java
package test;
import java.util.Comparator;
public class Less implements Comparator{
public int compare(Comparable x,Comparable y) {
return y.compareTo(x);
}
}
Test.java
package test;
import java.util.*;
public class Test {
public static void main(String[] args) {
Integer a[]= {1,2,5,8,9,0,3,4,6,7},i,j;
String b[]= {"AoMen","Beijing","ShangHai","ChongQing","TianJin","XiangGang"};
Double c[]= {0.5,3.7,6.3,8.5,9.2,1.7,2.3,4.1,5.9,7.4};
ArrayList A=new ArrayList();
for(i=0;i<10;i++)
A.add(a[i]);
Vector B=new Vector();
for(i=0;i<6;i++)
B.add(b[i]);
LinkedList C=new LinkedList();
for(i=0;i<10;i++)
C.add(c[i]);
j=LinearList.partition((List)A, 0, 9, new Greater());
System.out.println(A);
System.out.println(j);
j=LinearList.partition((List)B, 0, 5, new Less());
System.out.println(B);
System.out.println(j);
j=LinearList.partition((List)C, 0, 9, new Greater());
System.out.println(C);
System.out.println(j);
}
}