首页 > 编程语言 > 详细

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

时间:2014-10-28 11:36:20      阅读:267      评论:0      收藏:0      [点我收藏+]

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

bubuko.com,布布扣
 1     static void sort(int [] a, int l,int r){
 2         int m = l+r>>1;
 3         int i=l, j = r;
 4         do{
 5             while( a[i]<a[m] ) i++;
 6             while( a[j]>a[m] ) j--;
 7             if( i<=j ){
 8                 int t = a[i];
 9                 a[i] = a[j];
10                 a[j] = t;
11                 i++; j--;
12             }
13         }while( i<j );
14         if( l<j ) sort(a,l,j);
15         if( r>i ) sort(a,i,r);
16     }
sort

 

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

bubuko.com,布布扣
 1     static int unique(int [] a, int l,int r){
 2         int i = l;
 3         int j = i+1;
 4         while( j<=r ){
 5             while( j<=r&&a[j]<=a[i] ) j++;
 6             if( i+1<=r&&j<=r ){
 7                 a[i+1] = a[j];
 8                 i++;
 9                 j++;
10             }
11         }
12         
13         return i;
14     }
unique

 

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

bubuko.com,布布扣
1     static int lower_bound(int [] a,int l,int r,int x){
2         r++;l--;
3         while( r-l>1 ){
4             int m = l+r>>1;
5             if( a[m]<x ) l = m;
6             else r = m;
7         }
8         return r;
9     }
lower_bound

 

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

bubuko.com,布布扣
1     static int upper_bound(int [] a,int l,int r,int x){
2         r++; l--;
3         while( r-l>1 ){
4             int m = l+r>>1;
5             if( a[m]<=x ) l = m;
6             else r = m;
7         }
8         return r;
9     }
upper_bound

 

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

原文:http://www.cnblogs.com/llkpersonal/p/4056245.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!