【Java】数组元素的搜索

数组元素搜索

数组的搜索:从一个数组中搜索指定元素的索引位置;

搜索的方式:

(1)线性搜索:从头到位 / 从尾到头(indexOf / lastIndexOf)
但是这种搜索方式对于元素个数多的数组性能极低(最少搜索次数为1,最多搜索次数为N,平均搜索次数 (N+1) / 2)。

(2) 二分搜索法(折半查找法/二分搜索法):

1. 代码实现(线性搜索)


// 线性搜索
import java.util.ArrayList;
import java.util.List;
public class LinearSearch{
    public static void main(String args[]){
		
		int[] nums = new int[]{6,1,3,3,5,6,9,1};	
		int ele = 1;
		List<Integer> list = linearSearch(nums,ele);  
		for(int index : list){
			
			System.out.println(index);
		}
    }
	// 线性搜索
	public static List<Integer> linearSearch(int[] nums, int ele){
		
		List<Integer> list = new ArrayList<Integer>();		
		for (int i = 0 ; i < nums.length; i++){		
			if (nums[i] == ele){
			
				list.add(i);			
			}
		}	
		return list;	
	}
}

2. 代码实现(二分查找法)

// 二分查找法的前提:数组必须是有序的!
class BinarySearch 
{
	public static void main(String[] args) 
	{
		int[] nums = new int[]{4,3,2,5,1,99,22,23,11,21,8,6,9,18,919};
		selectSort(nums);
		printArray(nums);

		int index = binarySearch(nums,99);
		
		if (index == -1) // 判断元素是否存在
		{
			System.out.println("This element does not exist! ");
		}else{
			System.out.println(index);
		}		
	}

	// 二分查找法
	public static int binarySearch(int[] nums, int ele){

		int lowIndex = 0;
		int highIndex = nums.length-1;
		
		while(lowIndex <= highIndex){

			int midIndex = (lowIndex + highIndex) / 2;
			
			if ( ele < nums[midIndex])
			{
				highIndex = midIndex - 1;
			}

			else if(ele > nums[midIndex])
			{
				lowIndex = midIndex + 1;
			}
				
			else 
			{
				return midIndex;
			}
		}
		
		return -1;
	}
	
	// 选择排序
	public static void selectSort(int[] nums){
	
		for (int i = 0; i < nums.length-1 ; i++)
		{
			int minValueIndex = i;
			for(int j = 0; j < nums.length-1-i; j++){
			
				if (nums[minValueIndex] > nums[i+j+1])
				{
					minValueIndex = i+j+1;				
				}
			}
		int temp = nums[i];
		nums[i] = nums[minValueIndex];
		nums[minValueIndex] = temp;
		}	
	}	
	
	// 打印数组
	public static void printArray(int[] nums){		
		String res = "[";
		for (int i = 0; i < nums.length; i++){			
			res = res + nums[i];			
			if ( i != nums.length - 1){				
				res = res + ",";			
			}			
		}		
		res = res + "]";	
		System.out.println(res);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值