兩種查找方式

1.一般查找方式

import java.util.*;
class find 
{
	public static void main(String[] args) 
	{
		String str="hello World ";
		find_index(str,'o');
		//int[] a={1,3,5,7,9,11};
		//int m=search_half(a,1);
		//System.out.println(m);

	}
	public static int find_index(String str,char c){
		//先將字符串轉化爲數組
		char[] ch=str.toCharArray();
	
	for (int x=0;x<ch.length ;x++ )
	{
		if (c==ch[x])
		{
			System.out.println(x);
			return x;
		}
	}
	return -1;
	}
}
2.折半查找  (此種方法適用於已知排序的查找,效率較高)

import java.util.*;
class find 
{
	public static void main(String[] args) 
	{
		
		int[] a={1,3,5,7,9,11};
		int m=search_half(a,1);
		System.out.println(m);

	}
	
	//折半查找法
	public static int  search_half(int[] a,int b)
	{
	//char[] ch=str.toCharArray();
	//1 2 3 4 5 6 7      --->3   1,3,5,7,9,11
		int start=0;
		int len=a.length;//7
		int end=len;//  6
		int mid;
		while (start<end)
		{
			if (a[mid=(end+start)/2]>b)
			{
				end=mid;
			}
			else if (a[mid=(end+start)/2]<b)
			{
				start=mid;
			}
			else
			{
				return mid;
			}
				
		}
	return 0;
	}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章