Algorithm.Find(查找)

二分搜索

查找第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));

	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值