Algorithmic examination: copy, invert, search of array (linear search)

Algorithmic examination: copy, invert, search of array (linear search)

Topic description:
Examination of algorithm: copy, invert, and search of array (linear search)

Problem-solving ideas:
1. Copy (different from the assignment of array variables): You
 need to create a new array (the length is the same as the original array), and then traverse and assign values ​​to the elements in the new array one by one;
2. Reverse the array (note: It is to invert the original array instead of creating a new array) and
 introduce a temporary variable temp. This is the basic operation, but the range of i in the for loop should be corresponding. The index starts from 0.
3. Search (linear search): search There are many methods, here is the most stupid linear search
 traverse the array, and then judge whether it is equal, there are two methods, see the program

The Java code for this question:

import java.util.Arrays;

/*
 * 算法的考查:数组的复制、反转、查找(线性查找、二分法查找)
 * 
 */
public class ArrayTest2 {
    
    
	public static void main(String[] args) {
    
    
		String[] arr = new String[] {
    
    "hyj", "hxc", "hdh", "wt", "wtl", "yhp"};
		
		//1.数组的复制(区别于数组变量的赋值:arr1 = arr)
		String[] arr1 = new String[arr.length];
		for(int i = 0;i < arr1.length;i++){
    
    
			arr1[i] = arr[i];
		}
		System.out.println();
		//2.数组的反转 (注意:是将原数组反转,而不是新建一个数组)
		String temp;
		for(int i = 0;i <= arr1.length/2-1;i++){
    
    
			temp = arr1[i];
			arr1[i] = arr1[arr1.length-1-i];
			arr1[arr1.length-1-i] = temp;	
		}
		System.out.println(Arrays.toString(arr1)); //将数组输出,也可使用遍历
		
		//3.查找(或搜索)
		//线性查找:
		//线性查找-方法一:
		String dest = "hxc";
		boolean isFlag = true; //用作标识,只有没找到才会输出
		for(int i = 0;i < arr.length;i++){
    
    
			if(dest.equals(arr[i])){
    
    
				System.out.println("哈哈哈,找到你啦,位置为:" + i);
				isFlag = false;
				break;
			}
		}
		if(isFlag){
    
    
			System.out.println("很遗憾,没有找到!");
		}
		System.out.println();
		
		//线性查找-方法二:
		String dest1 = "hx";
		for ( int i = 0; i < arr.length; i++) {
    
    
			if (dest1.equals(arr[i])) {
    
    
				System.out.print("哈哈哈哈哈哈,找到你啦,位置为:" + i);
				
				break;
			}
			if (i == arr.length-1) {
    
      //这里length需要减1
				System.out.print("很遗憾,没有找到!");
			}
		}
		System.out.println();				
	}
}

Guess you like

Origin blog.csdn.net/qq_45555403/article/details/114221936