[模板总结] Java的一些模板

时间:2023-03-10 03:49:39
[模板总结] Java的一些模板

快速排序(数组a从小到大,参数1是待排序的数组,参数2是起始下标,参数3是终止下标):

     static void sort(int [] a, int l,int r){
int m = l+r>>1;
int i=l, j = r;
do{
while( a[i]<a[m] ) i++;
while( a[j]>a[m] ) j--;
if( i<=j ){
int t = a[i];
a[i] = a[j];
a[j] = t;
i++; j--;
}
}while( i<j );
if( l<j ) sort(a,l,j);
if( r>i ) sort(a,i,r);
}

sort

Unique函数(类似C++的unique,返回值是最后一个的数的下标,参数1是待排序的数组,参数2是起始下标,参数3是终止下标)

     static int unique(int [] a, int l,int r){
int i = l;
int j = i+1;
while( j<=r ){
while( j<=r&&a[j]<=a[i] ) j++;
if( i+1<=r&&j<=r ){
a[i+1] = a[j];
i++;
j++;
}
} return i;
}

unique

lower_bound二分查找(类似C++的lower_bound,参数1是待查找数组,参数2是起始下标,参数3是终止下标,参数4是找的数,返回第一个>=x的位置)

     static int lower_bound(int [] a,int l,int r,int x){
r++;l--;
while( r-l>1 ){
int m = l+r>>1;
if( a[m]<x ) l = m;
else r = m;
}
return r;
}

lower_bound

upper_bound二分查找(用法同上,返回值为第一个>x的位置)

     static int upper_bound(int [] a,int l,int r,int x){
r++; l--;
while( r-l>1 ){
int m = l+r>>1;
if( a[m]<=x ) l = m;
else r = m;
}
return r;
}

upper_bound