Showing posts with label 算法. Show all posts
Showing posts with label 算法. Show all posts

Tuesday, April 7, 2015

mysql两种计算坐标距离的方法

SET @lat = 33;
SET @lon = -98;
SELECT count(*) FROM pecker_db.d_zip_lookup
where MBRContains(
              LineString
                        (
                        Point
                                 (
                                 @lon + 100 / ( 111.1 / COS(RADIANS(@lat))),
                                    @lat + 100 / 111.1
                                 ),
                        Point    (
                                 @lon - 100 / ( 111.1 / COS(RADIANS(@lat))),
                                    @lat - 100 / 111.1
                                 )
                        ),
                   my_point)

使用mbrcontains方法,需要自己my_point blob位置属性
实际上是一个矩形,较慢


SET @lat = 33;
SET @lon = -98;  
SELECT (6371 * acos( cos( radians(lat_loc) ) * cos( radians( @lat ) ) * cos( radians( @lon ) - radians(lng_loc) ) + sin( radians(lat_loc) ) * sin( radians( @lat ) ) ) ) as distance
FROM pecker_db.d_zip_lookup
 where lat_loc between @lat-2 and @lat+2
and lng_loc between @lon-2 and @lon+2
having distance<100;
速度快,关键的地方在于划定区域来计算

参考http://geography.about.com/library/faq/blqzdistancedegree.htm

Sunday, December 21, 2014

快速排序实现

注:此快速排序取第一个值为pivot,把小于pivot的数放到左边,大于的放到右边

public class QuickSort {

public static void main(String[] args) {
int arr[]=new int[50];
for(int i=0;i<arr.length;i++)
arr[i]=(int)(Math.random()*100);
//int arr[]={ 49, 42, 36};
//..int arr[]={8,7,8,8};
//for(int i=0;i<arr.length;i++){
// System.out.print(arr[i]+" ");
//}
System.out.println();
quickSort(arr,0,arr.length-1);
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+", ");
}

}
public static void quickSort(int[] array,int start,int end){
int temp;

if(start>=end){return;}//大于号非常重要,如果没有,会导致index越界
if(start==end-1){        //base condition,两个数的比较,必须有
if(array[start]>array[end]){
temp=array[start];
array[start]=array[end];
array[end]=temp;
return;
}else
return;
}
int pivot=array[start];

int i=start+1;
int j=end;
while(i<j){
while(array[i]<=pivot&i!=end){//注意=很重要,否则无限循环
i++;
if(i==end&array[i]<pivot){
//非常重要,这是极端情况,考虑到如果pivot取的是最大值的情况
array[start]=array[end];
array[end]=pivot;
quickSort(array, start, i-1 );
return;
}
}
while(array[j]>=pivot&j!=start){
j--;
}
temp=array[j];
//i,j交换后需要交换回来,例如8(start),0,3,16(j),5(i),18,12,9    i=4,j=3
array[j]=array[i];
array[i]=temp;

}
temp=array[j];
array[start]=array[i];
array[j]=pivot;
array[i]=temp;
//System.out.println("j="+j+" start="+start);
quickSort(array, start, j-1 );
quickSort(array,j+1,end);

}
}
0, 1, 1, 2, 2, 3, 4, 15, 16, 17, 19, 22, 25, 27, 30, 36, 40, 41, 46, 46, 51, 53, 55, 55, 58, 59, 63, 64, 64, 65, 66, 66, 72, 73, 73, 74, 77, 78, 78, 78, 81, 81, 81, 86, 91, 92, 95, 99, 99, 99,