Search algorithm ------ sequential search

Search algorithm

Sequential search

Linear search

Let's look at a topic

The distribution of HKUST’s student performance is as follows: 1,8,10,89,1000,1234

Requirement: Determine whether the sequence contains a specific value (I will not give an example here) and display it directly in the title

Return value and subscript when found

Code

//顺序查找算法
//@author 王
public class SeqSearch {
    
    
	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		int arr[] = {
    
    1,9,11,-1,34,89};//无序的数组
		int index = seqSearch(arr, 89);
		if(index == -1){
    
    
			System.out.println("没有查找到我们的值");
		}else{
    
    
			System.out.println("下标为"+index);
		}	
	}
	//这里是找到一个符合的值就返回了
	public static int seqSearch(int[] arr,int value) {
    
    
		//线性查找是逐一比对,发现相同值时,返回
		for (int i = 0; i < arr.length; i++) {
    
    
			if(arr[i] == value){
    
    
				return i;
			}
		}
		return -1; 
	}
}

What if our value is not one? What if our array has two identical values, or multiple identical values?

Code

public class SeqSearch {
    
    
	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
    	int arr[] = {
    
    89,1,9,11,-1,34,89,89};//无序的数组
		ArrayList index = seqSearch1(arr, 89);
		if(index.size() == 0)
		{
    
    
			System.out.println("没有找到");
		}else{
    
    
			for (int i = 0; i < index.size(); i++) {
    
    
				System.out.println(index.get(i));
			}
		}
    }
	//这里找到可能是同样的值的多个情况
	public static ArrayList seqSearch1(int[] arr,int value) {
    
    
		ArrayList result = new ArrayList();
		int index=0;//辅助我们像结果数组中插入数据
		//线性查找是逐一比对,发现相同值时,返回
		for (int i = 0; i < arr.length; i++) {
    
    
			if(arr[i] == value){
    
    
				result.add(i);
			}
		}
		return result;
	}
}

Here I did not use an array to store our subscripts, saving unnecessary trouble, such as out of bounds, difficult to determine whether to find, etc., but used our ArrayList can dynamically control our length, and avoid, if The index of the data found is 0, and the array is not easy to judge

Of course

Our sequential search can also be searched according to our conditions. Of course, the code needs to be changed in response. We will not elaborate here. If you are interested, you can delve into it yourself, and I will share it when you encounter related topics later.

Guess you like

Origin blog.csdn.net/qq_22155255/article/details/112847028