查找数组元素

线性查找和二分查找

Posted by Ruizhi Ma on May 9, 2019

线性查找

package array;

public class ArrayLinearSearch {

	public static void main(String[] args) {
		//targer array
		int[] arr = new int[] {12,23,5,4,656,76};
		
		//target element
		int target = 5;
		
		//the index of target element
		int index = -1;
		
		//traversing the arry to search target element
		for(int i = 0;i < arr.length;i++){
			if(arr[i] == target){
				index = i;
				break;
			}
		}
		
		//print the index of target element
		System.out.println("index:" + index);
	}

}

运行结果:
index:2

二分查找(只适用于对有序数组进行查找)

package array;

public class ArrayBinarySearch {

	public static void main(String[] args) {
		//target array
		int[] arr = new int[] {1,2,3,4,5,6,7,8,9,10};
		
		//target element
		int target = 8;
		
		//the index of target element
		int index = -1;
		
		//record the start, end and middle position
		int begin = 0;
		int end = arr.length - 1;
		int mid = (begin + end)/2;
		
		//cycling to split the array and search target element
		while(true){
			
			if(begin >= end){
				break;
			}
			//If the middle element equals to the target element
			if(arr[mid] == target){
				index = mid;
				break;
			}else{
				//If the middle element less than the target element
				if(arr[mid] < target){
					begin = mid + 1;
				//If the middle element more than the target element
				}else{
					end = mid - 1;
				}
				
				//reassisgn new value to mid
				mid = (begin + end)/2;
			}
		}
		System.out.println("index:" + index);
	}

}

运行结果:
index:7

小总结

后来又把线性查找和二分查找,运用面向对象的编程思想加入到昨天写的对数组进行操作的代码里面去了,不过写在本地了,博客上面我就不添加了,单独拎出来发一下。