您的位置:首页 > 编程语言 > Go语言

Algorithm.Find(查找)

2016-04-17 20:39 495 查看
二分搜索

查找第K小

package Algorithm.Find;
import java.util.Collections;
import java.util.Vector;
/*Author: CPlusPlus小码农
*If any question,
*Please contact:
* http://daixiecplusplus.blog.163.com/ * QQ:1926742804
*/
public class BinarySearch<E extends Comparable<E> > {
public int BSearch(Vector<E> v, E value)
{
int low = 0;
int high = v.size()-1;
int mid;
E temp;
while(low <= high)
{
mid = (low+high)/2;
temp = v.get(mid);
if( temp.compareTo(value) == 0) return mid;
else if(temp.compareTo(value) < 0)
{
low = mid+1;
}
else
{
high = mid-1;
}
}
return -1;
}

public int BSearchByExcursion(Vector<E> v,E value,int low,int high)
{
if(low > high) return -1;
else
{
int mid = (low+high)/2;
E temp = v.get(mid);
if(temp.compareTo(value) == 0) return mid;
else if(temp.compareTo(value) < 0)
{
return BSearchByExcursion(v,value,mid+1,high);
}else return BSearchByExcursion(v,value,low,mid-1);
}
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BinarySearch<Integer> bs = new BinarySearch<Integer>();

Vector<Integer> v = new Vector<Integer>();
v.add(10);
v.add(20);
v.add(50);
v.add(100);
v.add(15);
v.add(60);
Collections.sort(v);

System.out.println(bs.BSearch(v, 5));
System.out.println(bs.BSearch(v, 50));
System.out.println(Collections.binarySearch(v, 50));

System.out.println(bs.BSearchByExcursion(v, 5, 0, v.size()-1));
System.out.println(bs.BSearchByExcursion(v, 50, 0, v.size()-1));
}

}
package Algorithm.Find;
import java.util.Iterator;
import java.util.Vector;

import Structure.BSTree.BSTree;
/*Author: CPlusPlus小码农
*If any question,
*Please contact:
* http://daixiecplusplus.blog.163.com/ * QQ:1926742804
*/
public class FindKthMin<E extends Comparable<E> > {
public E Find_KthMin(Vector<E> v, int kth)
{
BSTree<E> tree = new BSTree<E>();
Iterator<E> i = v.iterator();
while(i.hasNext())
{
tree.Insert(i.next());
}
return tree.FindKth(kth);
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Vector<Integer> v = new Vector<Integer>();
v.add(10);
v.add(50);
v.add(20);
v.add(30);
v.add(40);

FindKthMin<Integer> fkth = new FindKthMin<Integer>();
System.out.println(fkth.Find_KthMin(v, 5));

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java 算法 查找