java: algorithm questions (continuously updated)

Question 1: Calculation of eigenvalues

Case: Define a one-dimensional array of int type, containing 10 elements, assign some random integers respectively, and then find the maximum value, minimum value, sum, and average of all elements, and output them.

Requirement: All random numbers are two digits: [10,99]
Tip: Find a random number in the range [a,b]: (int)(Math.random() * (b - a + 1)) + a;

Answer:

package com.atguigu3.common_algorithm.exer1;

/**
     案例:定义一个int型的一维数组,包含10个元素,分别赋一些随机整数,然后求出所有元素的最大值,最小值,总和,平均值,并输出出来。

public class ArrayExer01 {
    public static void main(String[] args) {
        //1. 动态初始化方式创建数组
        int[] arr = new int[10];
        //2. 通过循环给数组元素赋值
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int)(Math.random() * (99 - 10 + 1)) + 10;
            System.out.print(arr[i] + "\t");
        }

        System.out.println();

        //3.1 求最大值
        int max = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if(max < arr[i]){
                max = arr[i];
            }
        }
        System.out.println("最大值为:" + max);

        //3.2 求最小值
        int min = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if(min > arr[i]){
                min = arr[i];
            }
        }
        System.out.println("最小值为:" + min);


        //3.3 求总和
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }
        System.out.println("总和为:" + sum);

        //3.4 求平均值
        int avgValue = sum / arr.length;
        System.out.println("平均值为:" + avgValue);


    }
}

operation result

Code explanation: 

The above code is a Java program that creates a one-dimensional array containing 10 random integers, calculates the maximum, minimum, sum, and average of the array, and then outputs these values. The following is the main explanation of the code: 1. First, create an integer array `arr` containing 10 elements through the following code, and allocate memory space using dynamic initialization: ```java int[] arr = new int[10] ; ``` 2. Use a loop to assign a random integer value to each element of the array from 0 to 9. These random integers range from 10 to 99: ```java for (int i = 0; i < arr.length; i++) { arr[i] = (int)(Math.random() * (99 - 10 + 1)) + 10; System.out.print(arr[i] + "\t") ; } ``` This loop uses the `Math.random()` method to generate a random decimal number between 0 and 1, then scales it to the integer range between 10 and 99, and stores the result in the corresponding position of the array . At the same time, the code also prints the element values ​​of the array. 3. Next, calculate the maximum, minimum, sum and average of the array: - Find the maximum value (3.1): First, create a variable `max` and initialize it to the first element of the array `arr[0 ]`. Then, use a loop to iterate through all elements of the array, and update the value of `max` if the current element is greater than `max`. Ultimately, `max` will contain the maximum value of the array. - Find the minimum value (3.2): Similarly, create a variable `min` and initialize it to the first element of the array `arr[0]`. Then, use a loop to iterate through all elements of the array, and update the value of `min` if the current element is smaller than `min`. Ultimately, `min` will contain the minimum value of the array. - Summing (3.3): Create a variable `sum` and initialize it to 0. Then, use a loop to iterate over all elements of the array, adding the value of each element to `sum`. Ultimately, `sum` will contain the sum of all elements of the array. - Find the average (3. 4): To calculate the average, just divide the sum `sum` by the length of the array `arr.length`. The result will be stored in the `avgValue` variable. 4. Finally, the code prints the calculated maximum, minimum, sum, and average values ​​to the console. This code demonstrates how to create and manipulate one-dimensional arrays and perform some basic mathematical calculations.

 Question 2: Calculation of eigenvalues

Case: Judges’ scoring

Analyze the following requirements and implement them with code:

(1) In the programming competition, there are 10 judges who score the contestants. The scores are: 5, 4, 6, 8, 9, 0, 1, 2, 7, 3

(2) Find the player’s final score (the average of the remaining 8 judges’ scores after removing the highest score and the lowest score)

Answer

package com.atguigu3.common_algorithm.exer2;

/**
 *      (1)在编程竞赛中,有10位评委为参赛的选手打分,分数分别为:5,4,6,8,9,0,1,2,7,3
 *      (2)求选手的最后得分(去掉一个最高分和一个最低分后其余8位评委打分的平均值)
 */
public class ArrayExer02 {
    public static void main(String[] args) {

        int[] scores = {5,4,6,8,9,0,1,2,7,3};
        //声明三个特征值
        int sum = 0;
        int max = scores[0];
        int min = scores[0];

        for (int i = 0; i < scores.length; i++) {
            sum += scores[i]; //累加总分
            //用于获取最高分
            if(max < scores[i]){
                max = scores[i];
            }
            //用于获取最低分
            if(min > scores[i]){
                min = scores[i];
            }
        }

        int avg = (sum - max - min) / (scores.length - 2);
        System.out.println("去掉最高分和最低分之后,平均分为:" + avg);


    }
}

operation result;

Code explanation

This code is a Java program used to calculate the average score of the remaining 8 judges after removing the highest score and the lowest score when 10 judges score contestants in a programming competition. Here is a detailed explanation of the code:

1. First, an integer array `scores` is defined, which contains the scores given to the contestants by 10 judges.

2. Next, three integer variables are declared: `sum`, `max` and `min`, used to represent the total score, the highest score and the lowest score respectively. Initially, these variables are initialized to the first element in the array `scores[0]`, which is the initial value for subsequent comparison to find the highest and lowest scores.

3. Use a `for` loop to iterate through each element in the array `scores`, calculate the total score and find the highest and lowest scores.

   - In the loop, accumulate the scores of each judge into the `sum` variable through `sum += scores[i]` to calculate the total score.

   - Find the highest and lowest scores through conditional judgment statements. The `max` variable records the highest score. If the current judge's score is greater than `max`, then `max` is updated to the current score; the `min` variable records the lowest score. If the current judge's score is smaller than `min`, then `max` is updated. min` is the current score.

4. Calculate the average score `avg`, using the formula `(sum - max - min) / (scores.length - 2)`. Here the highest and lowest scores are subtracted, and divided by the length of the array minus 2, because one highest score and one lowest score are removed.

5. Finally, use `System.out.println` to print out the average score after excluding the highest score and the lowest score.

Summary: This code mainly calculates the total score by traversing the array, finds the highest score and the lowest score, then calculates the average score after excluding the highest score and the lowest score according to the prescribed formula, and prints the result. This method can eliminate some unfair factors in the competition, such as the impact of particularly high or low scores from individual judges on the total score of the contestants.

Question 3: Yang Hui Triangle 1

Case: Use a two-dimensional array to print a 10-line Yang Hui triangle.

   hint:
   1. The first row has 1 element, and the nth row has n elements.
   2. The first element and the last element of each row are both 1
   3. Starting from the third row, for elements other than the first element and the last element. Right now:
   yanghui[i][j] = yanghui[i-1][j-1] + yanghui[i-1][j];

Answer;

package com.atguigu3.common_algorithm.exer3;

public class YangHuiTest {
    public static void main(String[] args) {

        //1. 创建二维数组
        int[][] yangHui = new int[10][];

        //2.使用循环结构,初始化外层数组元素
        for(int i = 0;i < yangHui.length;i++){
            yangHui[i] = new int[i + 1];
            //3. 给数组的元素赋值
            //3.1 给数组每行的首末元素赋值为1
            yangHui[i][0] = yangHui[i][i] = 1;
            //3.2 给数组每行的非首末元素赋值
            //if(i >= 2){
                for(int j = 1;j < yangHui[i].length - 1;j++){ //j从每行的第2个元素开始,到倒数第2个元素结束
                    yangHui[i][j] = yangHui[i - 1][j] + yangHui[i - 1][j - 1];
                }
            //}

        }
        //遍历二维数组
        for (int i = 0; i < yangHui.length; i++) {
            for (int j = 0; j < yangHui[i].length; j++) {
                System.out.print(yangHui[i][j] + "\t");
            }
            System.out.println();
        }


    }
}

operation result:

Code explanation:

Overall understanding:

This code is a Java program that generates and prints the first ten lines of Yang Hui's triangle. Here is an explanation of the code:

1. `int[][] yangHui = new int[10][];`: In this line of code, a two-dimensional integer array named `yangHui` is created, which has 10 rows. Please note that since each row of Yang Hui's triangle has a different length, only the outer array is initialized here, and the inner array will be initialized in subsequent loops.

2. Use a `for` loop structure to initialize the elements of the outer array. `for(int i = 0;i < yangHui.length;i++)`: This loop iterates the variable `i` from 0 to 9, corresponding to the first 10 rows of Yang Hui's triangle.

3. In each loop, perform the following operations:
   - `yangHui[i] = new int[i + 1];`: Create a new one-dimensional array with a length of `i + 1` and assign it to The `i`th element of the outer array `yangHui`. This step actually initializes the inner array, making the outer array `yangHui` become a two-dimensional array that stores each row of data.
   - `yangHui[i][0] = yangHui[i][i] = 1;`: Set the first and last elements of each row to 1, because the first and last elements of each row of Yang Hui's triangle are 1 .

4. Under the code segment `//3.2 Assigning values ​​to the non-first and last elements of each row of the array` in the comments, there is an inner loop used to assign values ​​to the non-first and last elements of the inner array. This part of the code is commented out, but it is actually the core calculation of Yang Hui's triangle.

   - `for(int j = 1;j < yangHui[i].length - 1;j++)`: This loop starts from the second element of each row and ends with the second to last element, because the first and last elements are already in The value assigned in the previous code is 1.
   - `yangHui[i][j] = yangHui[i - 1][j] + yangHui[i - 1][j - 1];`: This line of code calculates the value of the non-first and last elements of the current row, which is equal to the above The sum of the elements of the same column in a row and the elements of the previous column in the previous row. This is a characteristic of Yang Hui's triangle, where each element is equal to the sum of the two elements above it.

5. Finally, traverse the two-dimensional array through two nested `for` loops and print the value of each element using `System.out.print` to create the shape of Yang Hui's triangle.

In short, this code generates a two-dimensional array containing the first ten rows of data of Yang Hui's triangle and prints it out, showing the structure of Yang Hui's triangle. Each element is the sum of the two elements above it.

Understand in sections:

1. Understanding of the step yangHui[i] = new int[i + 1]

This line of code `yangHui[i] = new int[i + 1];` is an operation used to initialize the inner array of each row of Yang Hui's triangle. Let me explain in detail what this step means:

- `yangHui[i]`: This means accessing the `i` row (the element of the outer array) of the two-dimensional array `yangHui`, where `i` is the loop variable, which represents the index of the current row.

- `new int[i + 1]`: Here we create a new one-dimensional array of integers and assign it to the element of row `i`. `i + 1` represents the length of the array in the current row, because in Yang Hui's triangle, the length of each row is increasing. The first row has one element, the second row has two elements, and the third row has three elements. And so on. Therefore, we use `i + 1` to represent the length of the current line.

With this line of code, we create an inner array for each row in the outer array `yangHui`. The length of this inner array is equal to the number of rows in the current row (`i + 1`). This is because the number of elements in each row is different, so we need to create inner arrays of different lengths when initializing each row to store the elements of that row.

2. Understanding of yangHui[i][0] = yangHui[i][i] = 1;

This line of code `yangHui[i][0] = yangHui[i][i] = 1;` is used to initialize the first and last elements of each row of Yang Hui's triangle to 1. Let me explain in detail what this step means:

- `yangHui[i]` means accessing the `i` row of the two-dimensional array `yangHui`, where `i` is a loop variable representing the index of the current row.

- `[0]` means accessing the first element of the current row, which is the first element of the row.

- `[i]` means accessing the last element of the current line, which is the last element of the line. In Yang Hui's triangle, the first and last elements of each row are 1.

- `=` is the assignment operator, assigning the value on the right to the element on the left.

Therefore, this line of code actually sets the first and last elements of the current row to 1. This is because in Yang Hui's triangle, the first and last elements of each row are 1, which is a characteristic of Yang Hui's triangle. The elements inside other rows are obtained by adding the elements in the adjacent previous row, and the first and last elements are fixed to 1.

Three for(int j = 1;j < yangHui[i].length - 1;j++){ //j starts from the 2nd element of each row and ends with the 2nd element from the last yangHui[i][j]
                  = yangHui[i - 1][j] + yangHui[i - 1][j - 1];
                }Understanding of this code

This code is used to calculate the value of the non-head and tail elements of each row of Yang Hui's triangle. It is the core part of Yang Hui's triangle generation. Let me explain in detail what this code means:

```java
for(int j = 1;j < yangHui[i].length - 1;j++){     yangHui[i][j] = yangHui[i - 1][j] + yangHui[i - 1][ j - 1]; } ```


- `for(int j = 1; j < yangHui[i].length - 1; j++)`: This is an internal loop, which is used to traverse the elements inside the current row, starting from the 2nd element (`j `The initial value is 1) until the end of the second to last element (`yangHui[i].length - 1` means the length of the current line minus 1).

- `yangHui[i][j]`: This is to access the `j`th element of the current row `i` in the two-dimensional array `yangHui`. `i` represents the index of the current row, and `j` represents the index of the current element in the current row.

- `yangHui[i - 1][j]`: This is the value that accesses the element of the same column `j` of the previous row `i - 1`.

- `yangHui[i - 1][j - 1]`: This is the value that accesses the element of the previous column `j - 1` of the previous row `i - 1`.

The purpose of this line of code is to calculate the elements inside the current row `i` whose value is equal to the sum of the elements of the same column of the previous row and the elements of the previous column of the previous row. This is a property of Yang Hui's triangle: each interior element is the sum of the two elements above it. Through this loop, the internal elements of each row of Yang Hui's triangle are correctly calculated and assigned. In this way, the entire Yang Hui triangle is generated.

Explain in detail

When generating a Yang Hui triangle, the internal elements of each row (except the first and last elements) are obtained by adding the adjacent elements of the previous row. Let me explain in detail how this code works:

1. The outer loop `for(int i = 0; i < yangHui.length; i++)` traverses each row (from row 0 to row 9).

2. The inner loop `for(int j = 1; j < yangHui[i].length - 1; j++)` traverses the internal elements of the current row, from the 2nd element to the 2nd to last element (because the beginning and end of each row The elements are all 1, so no need to count them).

3. In the inner loop of each row, use the following formula to calculate the element value of the current row:
   
   `yangHui[i][j] = yangHui[i - 1][j] + yangHui[i - 1][j - 1] ;`

   The meaning of this formula is that the `j`th element of the current row is equal to the sum of the `j`th element of the previous row and the `j - 1`th element of the previous row. This is one of the properties of Yang Hui's triangle: each interior element is the sum of the two elements above it.

   For example, for the inner elements of the third row (counting from 0), the calculation is as follows:

   - `yangHui[2][1] = yangHui[1][1] + yangHui[1][0]`, that is, the second element of row 3 is equal to the second element of row 2 and the second element of row 2 The sum of the first elements.
   - `yangHui[2][2] = yangHui[1][2] + yangHui[1][1]`, that is, the 3rd element in line 3 is equal to the 3rd element in line 2 and the 2nd element in line 2 The sum of the 2nd elements.

4. This inner loop will calculate the correct values ​​for all inner elements of the current row. This way, each row will be correctly populated at the end of the loop, with each element representing the corresponding value in Yang Hui's triangle.

Summary: The above code snippet is actually generating part of Yang Hui's triangle, by calculating the internal elements of each row, ensuring that each internal element satisfies the rules of Yang Hui's triangle, that is, it is equal to the sum of the two elements above it. This method is repeated line by line, and finally the shape of the entire Yang Hui triangle is formed. Hopefully the explanation is clearer this time!

Question 4: Yang Hui Triangle 2

Given a non-negative integer  numRows, generate the forward direction of "Yang Hui Triangle"  numRows .

In "Yang Hui's Triangle", each number is the sum of the numbers on its upper left and upper right.

Example 1:

Input: numRows = 5
 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2:

Input: numRows = 1
 Output: [[1]]

hint:

  • 1 <= numRows <= 30

Question 4: Yang Hui Triangle 3

Given a non-negative index  rowIndex, return the row of "Yang Hui Triangle"  rowIndex .

In "Yang Hui's Triangle", each number is the sum of the numbers on its upper left and upper right.

Example 1:

Input: rowIndex = 3
 Output: [1,3,3,1]

Example 2:

Input: rowIndex = 0
 Output: [1]

Example 3:

Input: rowIndex = 1
 Output: [1,1]

hint:

  • 0 <= rowIndex <= 33

Question 5: Assignment of arrays

Use simple arrays
(1) Create a class named ArrayTest and declare two variables, array1 and array2, in the main() method. They are arrays of type int[].
(2) Use curly brackets {} to initialize array1 to 8 prime numbers: 2, 3, 5, 7, 11, 13, 17, 19.
(3) Display the contents of array1.
(4) Assign array2 variable equal to array1, modify the even index element in array2 to make it equal to the index value (such as array[0]=0, array[2]=2).
(5) Print out array1.

code

package com.atguigu3.common_algorithm.exer4;


public class ArrayExer04 {
    public static void main(String[] args) {
        //(1)创建一个名为ArrayExer04的类,在main()方法中声明array1和array2两个变量,他们是int[]类型的数组。
        int[] array1,array2;
        //(2)使用大括号{},把array1初始化为8个素数:2,3,5,7,11,13,17,19。
        array1 = new int[]{2,3,5,7,11,13,17,19};
        //(3)显示array1的内容。
        for (int i = 0; i < array1.length; i++) {
            System.out.print(array1[i] + "\t");
        }
        //(4)赋值array2变量等于array1,修改array2中的偶索引元素,使其等于索引值(如array[0]=0,array[2]=2)。
        array2 = array1;
        System.out.println();
        System.out.println(array1);  //[I@58372a00
        System.out.println(array2);   //[I@58372a00

        for (int i = 0; i < array2.length; i++) {
            if(i % 2 == 0){
                array2[i] = i;
            }
        }

        System.out.println();//换行
        //(5)打印出array1。
        for (int i = 0; i < array1.length; i++) {
            System.out.print(array1[i] + "\t");
        }
    }
}

operation result:

Memory analysis

Code explanation

The above code is a Java program whose purpose is to demonstrate the initialization, assignment and modification of array elements. Here's a step-by-step explanation of the code:

1. First, define a Java class named `ArrayExer04` and perform operations in the `main` method of the class.

2. In lines 2 and 3, two `int` array variables `array1` and `array2` are declared, but they are not initialized. This means that they are currently empty arrays, with no memory space allocated to store integer elements.

3. In line 5, the `array1` array is initialized using curly braces `{}` and assigned to an array containing 8 prime numbers: 2, 3, 5, 7, 11, 13, 17, 19.

4. Next, use a `for` loop in lines 7 to 12 to iterate and print the contents of the `array1` array. This will output all prime numbers in the array.

5. On line 14, initialize `array2` to `array1`. This means that `array2` and `array1` now refer to the same array object, they point to the same memory location.

6. In lines 16 and 17, print the memory addresses of `array1` and `array2` respectively. Since they refer to the same array, their memory addresses will be the same.

7. Next, in lines 20 to 25, use a `for` loop to traverse the even index positions (0, 2, 4, 6) of the `array2` array and modify the elements at these positions to be equal to their The index values ​​are equal. This means that elements at even index positions will change to 0, 2, 4, 6, while elements at odd index positions will remain unchanged.

8. Finally, in lines 27 to 32, traverse and print the contents of the `array1` array again. Since `array1` and `array2` refer to the same array, the elements in the array have been modified, so the output will show the modified values.

It should be noted that since `array1` and `array2` refer to the same array object, modifications to one of the arrays will also affect the other array because they actually point to the same memory space. This is because in line 14, `array2` is assigned `array1`, which just copies the reference to `array2` instead of creating a new array.

Question 6: Copying Arrays

Case: copy, assignment

Use simple arrays
(1) Create a class named ArrayTest and declare two variables, array1 and array2, in the main() method. They are arrays of type int[].
(2) Use curly brackets {} to initialize array1 to 8 prime numbers: 2, 3, 5, 7, 11, 13, 17, 19.
(3) Display the contents of array1.
(4) Assign array2 variable equal to array1, modify the even index element in array2 to make it equal to the index value (such as array[0]=0, array[2]=2).
(5) Print out array1.

Thinking: What is the relationship between array1 and array2?
[answer]array1 and array2 are two variables that jointly point to the same array structure in the heap space. That is, the address values ​​of both are the same.

Extension: Modify the question to realize the copying of array1 array by array2

code

package com.atguigu3.common_algorithm.exer4;


public class ArrayExer04_1 {
    public static void main(String[] args) {
        //(1)创建一个名为ArrayExer04的类,在main()方法中声明array1和array2两个变量,他们是int[]类型的数组。
        int[] array1,array2;
        //(2)使用大括号{},把array1初始化为8个素数:2,3,5,7,11,13,17,19。
        array1 = new int[]{2,3,5,7,11,13,17,19};
        //(3)显示array1的内容。
        for (int i = 0; i < array1.length; i++) {
            System.out.print(array1[i] + "\t");
        }
        //(4)复制array1数组给array2,修改array2中的偶索引元素,使其等于索引值(如array[0]=0,array[2]=2)。
        array2 = new int[array1.length];
        for (int i = 0; i < array1.length; i++) {
            array2[i] = array1[i];
        }

        System.out.println();
        System.out.println(array1);  //[I@58372a00
        System.out.println(array2);   //[I@4dd8dc3

        for (int i = 0; i < array2.length; i++) {
            if(i % 2 == 0){
                array2[i] = i;
            }
        }

        System.out.println();//换行
        //(5)打印出array1。
        for (int i = 0; i < array1.length; i++) {
            System.out.print(array1[i] + "\t");
        }
    }
}

operation result:

Memory analysis

Code explanation

This code is similar to the previous code, but with one important difference: in step 4, it creates a new array when initializing `array2`, instead of assigning `array2` directly to a reference to `array1` . Here's a step-by-step explanation of the code:

1. First, define a Java class named `ArrayExer04_1` and perform operations in the `main` method of the class.

2. In lines 2 and 3, two `int` array variables `array1` and `array2` are declared, but they are not initialized. This means that they are currently empty arrays, with no memory space allocated to store integer elements.

3. In line 5, the `array1` array is initialized using curly braces `{}` and assigned to an array containing 8 prime numbers: 2, 3, 5, 7, 11, 13, 17, 19.

4. Next, use a `for` loop in lines 7 to 12 to iterate and print the contents of the `array1` array. This will output all prime numbers in the array.

5. On line 14, a new `array2` array is created with the same length as `array1`. This allocates a new memory space to store the elements of `array2`.

6. In lines 16 to 21, the elements of the `array1` array are copied to the `array2` array through a loop. Now, `array2` contains the same element values ​​as `array1`, but they are two different array objects.

7. Next, in lines 23 and 24, print the memory addresses of `array1` and `array2` respectively. Since they are two different array objects, their memory addresses will not be the same.

8. In lines 26 to 31, use a `for` loop to traverse the even index positions (0, 2, 4, 6) of the `array2` array and modify the elements at these positions to be equal to their index values. . This means that the elements at even index positions in `array2` will change to 0, 2, 4, 6, while the elements at odd index positions will remain unchanged.

9. Finally, in lines 33 to 38, traverse and print the contents of the `array1` array again. Since `array1` and `array2` are two different array objects, modifying `array2` will not affect `array1`, so the output will show the unmodified value.

In short, unlike the previous code, this time the code creates a new array `array2` and copies the value of `array1` to `array2`, making them two independent array objects, so modifying `array2` does not Will affect `array1`.

Question 7: Reverse of array elements

Case:
Define the array: int[] arr = new int[]{34,54,3,2,65,7,34,5,76,34,67};
How to achieve reversed storage of array elements? You have several methods.

code

package com.atguigu3.common_algorithm.exer5;


public class ArrayExer05 {
    public static void main(String[] args) {
        int[] arr = new int[]{34,54,3,2,65,7,34,5,76,34,67};

        //遍历
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + "\t");
        }
        System.out.println();

        //反转操作
        //方式1:
//        for(int i = 0;i < arr.length/2;i++){
//            //交互arr[i] 与 arr[arr.length - 1 - i]位置的元素
//            int temp = arr[i];
//            arr[i] = arr[arr.length - 1 - i];
//            arr[arr.length - 1 - i] = temp;
//        }
        //方式2:
        for(int i = 0,j = arr.length - 1;i < j;i++,j--){
            //交互arr[i] 与 arr[j]位置的元素
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }

        //方式3:不推荐
//        int[] newArr = new int[arr.length];
//        for(int i = arr.length - 1;i >= 0;i--){
//            newArr[arr.length - 1 - i] = arr[i];
//        }

//        arr = newArr;

        //遍历
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + "\t");
        }
    }
}

operation result:

Implementation idea: swap elements in symmetric positions of the array.

Code explanation

The above code is a Java program that mainly demonstrates how to reverse an integer array. Below I will explain line by line what this code does and how it works:

1. `int[] arr = new int[]{34,54,3,2,65,7,34,5,76,34,67};`: Define an integer array `arr` and initialize it to contain A set of integer values.

2. Traverse the array elements and print: Use a `for` loop to traverse the elements in the array `arr`, and print each element separated by tabs to form a line of output.

3. Reverse operation: Next there are three different ways to reverse the elements in the array `arr`.

   a. **Method 1** (commented out): Use a `for` loop to exchange the positions of elements from the beginning to the middle of the array, exchange the first element with the first element from the last, and the second element with The penultimate element is swapped, and so on.

   b. **Method 2**: Use two indexes `i` and `j` to move from the beginning and end of the array to the middle respectively, exchange the positions of the elements, exchange the first element with the last element, and the second The element is swapped with the second to last element, and so on. This is a more common way of reversing an array.

   c. **Method 3** (commented out): Create a new integer array `newArr`, and then use a `for` loop to copy the elements in the original array `arr` from back to front to the new array `newArr `, and finally point `arr` to the new array `newArr`. This is an uncommon way of reversing an array and is generally not recommended.

4. Traverse the array again and print: Use another `for` loop to iterate through the elements in the reversed array `arr`, and print each element separated by tabs to form a line of output.

Finally, the code will output the elements in the original array `arr` and the reversed array elements to show the effects of different reversal methods. Generally, way 2 is the recommended way to reverse an array because it is simple and efficient. Way 1 and 3 are verbose and unnecessary.

Method 1 is explained in detail:

When using method one to reverse an array, it uses a loop that starts at the beginning and end of the array simultaneously, then swaps the positions of elements until it reaches the middle of the array. The following is a detailed explanation of method one:

1. Define an integer array `arr`, which contains a set of integer values.

2. Use a `for` loop to traverse the elements in the array. The condition of the loop is `i < arr.length/2`, which ensures that we only traverse the first half of the elements in the array.

3. In each iteration of the loop, we do the following:
   - Create an integer variable named `temp` to temporarily store the value of an element in the array.
   - Assign the value of the `i`th element of the array (i.e. `arr[i]`) to `temp` to save it.
   - Then, set the value of the `i`th element of the array to the value of the `i`th element from the bottom of the array (i.e. `arr[i] = arr[arr.length - 1 - i]`).
   - Finally, set the value of the penultimate `i` element of the array to `temp` to complete the exchange of elements.

4. When the loop completes, the elements in the entire array have been reversed.

5. Finally, use another `for` loop to iterate through the elements in the reversed array `arr` and print each element separated by tabs to form a line of output.

In this way, through method 1, the elements in the array are swapped pair by pair from front to back until the entire array is reversed. However, it should be noted that this method requires half more swap operations than the second method, so the efficiency is slightly lower. Method 2 uses two indexes to move from both ends of the array to the middle at the same time, requiring only half of the exchange operation, so it is more efficient.

Method 1 process:

arr.length=11
When i=0 i<11 arr[0]=34 temp =arr[0]=34

At this time, 34 in arr[0] is given to temp. At this time, the position of arr[0] is vacant.  

arr[0] = arr[11-1-0]   = arr[0] =arr[10] =67

At this time, give the value arr[10]=67 to arr[0]. At this time, arr[0] =67

At this time, our arr[10] will be free. 

At this time, we are giving 34 of temp to arr[10] and turning it into arr[10] =34

When i=1 i=2 i=3 i=4 i=5 and so on

arr[i] = arr[arr.length - 1 - i] How to understand

`arr[i] = arr[arr.length - 1 - i]` is a line of code used to implement the exchange operation of array elements. Let me explain what this line of code means:

- `i` is the index in the current loop iteration, representing the index of the first half of the array element.
- `arr[i]` represents the value of the element at index `i` in the array `arr`, which is the first element in the current iteration.
- `arr.length` represents the length of the array `arr`, which is the total number of elements in the array.
- `arr.length - 1 - i` calculates the index of the symmetric position in the array corresponding to the element with index `i`, that is, the index of another element that is exchanged with the current element.

Therefore, `arr[i] = arr[arr.length - 1 - i]` means to assign the value of the element with index `i` in the array to the element with index `arr.length - 1 - i` in the array. element. This operation is actually an element exchange, exchanging the positions of the `i`th element of the array and the `i`th element of the array.

This is a common technique used to reverse an array or exchange element positions. It uses two indexes to exchange elements in symmetric positions to achieve the purpose of array inversion.

When understanding the line of code `arr[i] = arr[arr.length - 1 - i]`, you can think about it in the following steps:

1. First, we need to understand what `arr[i]` and `arr[arr.length - 1 - i]` represent respectively:

   - `arr[i]` represents the value of the element with index `i` in the array `arr`.
   - `arr.length` represents the length of the array `arr`, which is the total number of elements in the array.
   - `arr.length - 1 - i` is a calculation that finds the index in the array of a position symmetrical to index `i`.

2. Consider a specific example to help understand. Suppose the array `arr` has 11 elements and the index is from 0 to 10, then the value of `arr.length` is 11.

   - When `i` is 0, `arr[0]` represents the first element of the array, and `arr[arr.length - 1 - 0]` represents the last element of the array (that is, the 11th element, since `arr.length - 1` is 10).

   - When `i` is 1, `arr[1]` represents the second element of the array, and `arr[arr.length - 1 - 1]` represents the penultimate element of the array.

   - By analogy, when `i` is 2, `arr[2]` represents the third element of the array, and `arr[arr.length - 1 - 2]` represents the third to last element of the array.

3. Therefore, the function of this line of code `arr[i] = arr[arr.length - 1 - i]` is to compare the value of the element with index `i` in the array `arr` to the value of the element with index `arr in the array. The values ​​of the elements of length - 1 - i` are exchanged.

The core idea of ​​this line of code is to use `i` to traverse backward from the front of the array, and at the same time use `arr.length - 1 - i` to traverse forward from the back of the array, and then exchange their element values ​​​​with each other to implement the array reversal operation. This swap operation causes the elements in the array to be swapped pair by pair from front to back, ultimately completing the inversion of the array. Hopefully this detailed explanation will help you better understand what this line of code does.

Method 2 is explained in detail:

Method 2 is a common method for reversing an array. It uses two index variables to move from both ends of the array to the middle, exchanging the positions of elements pair by pair. The following is a detailed explanation of method two:

1. First, define two integer variables `i` and `j`, which are respectively initialized to the index of the first element of the array (`i = 0`) and the index of the last element of the array (`j = arr.length - 1`). These two indices will point to the front and back ends of the array respectively.

2. Use a loop, usually a `for` loop, with the condition `i < j`, which ensures that the swap operation is only performed if the element pointed to by `i` comes before the element pointed to by `j`.

3. On each iteration of the loop, do the following:
   - Swap the values ​​of `arr[i]` and `arr[j]`. This means swapping the element at index `i` with the element at index `j` in the array.
   - Increment `i`, that is, move `i` one position to the right to point to the next element.
   - Reduce `j`, that is, move `j` one position to the left to point to the next element.

4. Continue looping and repeat step 3 until `i` is no longer less than `j`, which means the entire array has been reversed.

5. After the loop ends, the order of the elements in the array `arr` has been completely reversed.

The key idea of ​​this approach is to use two indexes, one from front to back and one from back to front, to gradually reduce the distance between them while exchanging the values ​​of the elements they point to. In this way, the elements in the array are swapped pair by pair from front to back, ultimately achieving the purpose of inverting the array.

This is an efficient and common way to reverse an array, because it only needs to traverse the array once and does not require additional arrays to store intermediate results, so it is better in performance than Method 1 and Method 3.

Method 2 process

When i=0 j=10;

When i=1 j=9;

When i=2 j=8;

When i=3 j=7;

When i=4 j=6;

When i=5 j=5;

When i=0 j=10

arr[0]=34;

temp =34 ;

At this time, arr[0] will be empty. 

Assign arr[10]=67 to arr[0]. At this time, arr[0] = 67; at this time, arr[10] is free. 

Then assign the value 34 of tmpe to arr[10]

This completes the exchange of arr[0] and arr[10]

Until i<j, that is, until i=4 j=6, there is no exchange.

Method 3 is explained in detail:

Method three is to reverse the original array by creating a new array. The following is a detailed explanation of method three:

1. First, define a new integer array `newArr`, the length of the array is the same as the length of the original array `arr`, that is, `int[] newArr = new int[arr.length];`. This new array is used to store the reversed elements.

2. Use a `for` loop, and the loop variable `i` starts from the last element of the original array and gradually decreases until `i` is 0.

3. In each iteration of the loop, copy the element `arr[i]` in the original array `arr` to the position `newArr[arr.length - 1 - i]` in the new array `newArr`, that is, the original The last element in the array is copied to the first position of the new array, the second-to-last element is copied to the second position of the new array, and so on.

4. When the loop ends, the elements in the new array `newArr` have been arranged in the reverse order of the original array `arr`, completing the array reversal operation.

5. Finally, you can choose to point the original array `arr` to the new array `newArr` so that the reversed array can be used in subsequent code. This is achieved via `arr = newArr;`.

It should be noted that although method three can achieve array reversal, it requires additional memory to store the new array `newArr`, so it is relatively inefficient in terms of space complexity. Method 2 is a more commonly used and efficient method, because it only requires the exchange of element positions on the original array and does not require additional arrays. So usually, method three is not as efficient as method two.

Method three process

When i=10

Copy the value of arr[11]=67 to the new array newArr[0]

newArr[0]=arr[10]=67

newArr[2]=arr[9]=34

That is, copy the last element in the original array to the first position of the new array, copy the second-to-last element to the second position of the new array, and so on.

Question 8: Expansion of Array

Case 1: Expansion of array:

Existing array int[] arr = new int[]{1,2,3,4,5};
Now expand the array length by 1, and add 10, 20, and 30 data to the arr array. How to operate?

code

package com.atguigu4.search_sort.exer1;

public class ArrayExer01_1 {
    public static void main(String[] args) {
        int[] arr = new int[]{1,2,3,4,5};

        //扩容1倍容量
//        int[] newArr = new int[arr.length * 2];
        //或
        int[] newArr = new int[arr.length << 1];

        //将原有数组中的元素复制到新的数组中
        for (int i = 0; i < arr.length; i++) {

            newArr[i] = arr[i];
        }

        //将10,20,30三个数据添加到新数组中
        newArr[arr.length] = 10;
        newArr[arr.length + 1] = 20;
        newArr[arr.length + 2] = 30;

        //将新的数组的地址赋值给原有的数组变量
        arr = newArr;

        //遍历arr
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + "\t");
        }
    }
}

operation result:

Code explanation

The above code is a Java program that demonstrates how to expand an integer array and add new elements to the expanded array. Let me explain each part of the code step by step:

1. Create a Java class named `ArrayExer01_1`.

2. In the `main` method, first create an initial integer array `arr`, which contains five integer elements: 1, 2, 3, 4, 5.

3. Next, you need to create a new integer array `newArr` to store the expanded elements. The length of the array `newArr` is twice the length of the original array `arr`, which is calculated by the bitwise operation `arr.length << 1`, which is equivalent to shifting the original length to the left by one bit, that is, multiplying by 2.

4. Use a `for` loop to copy the elements in the original array `arr` to the new array `newArr`. This loop iterates over each element in `arr` and copies them to `newArr` at the same index.

5. Next, add three new integer values ​​(10, 20, 30) to the new array `newArr`. They are added to the end of the original array `arr`, by indexing `arr.length`, `arr.length + 1` and `arr.length + 2`.

6. Finally, assign the reference of the new array `newArr` to the original array variable `arr`. This means that now `arr` refers to the expanded array, and the original array `arr` no longer refers to the original array, but points to the new array `newArr`.

7. The last `for` loop is used to traverse and print all elements in the array `arr` to show the results of expansion and element addition.

In short, this code demonstrates how to achieve expansion by creating a new, larger-capacity array, copying the elements of the original array to the new array, and then assigning the reference of the new array to the original array variable, thus The array expansion operation is completed.

Interpretation is done by indexing arr.length, arr.length + 1 and arr.length + 2.

In this part of the code, we are adding three new integer values ​​(10, 20, 30) to the new array `newArr`. These three values ​​will be added to the end of the new array.

First, we know that the length of the new array is twice the length of the original array `arr`, so the length of `newArr` is `arr.length * 2`. Since array indexing starts at 0, the valid index range of the new array is from 0 to `newArr.length - 1`.

1. `newArr[arr.length] = 10;`: This line of code adds the value 10 to the new array `newArr` at index position `arr.length`. Since `arr.length` is exactly equal to the length of the original array `arr`, this operation is equivalent to adding the value 10 to the end of the new array.

2. `newArr[arr.length + 1] = 20;`: This line of code adds the value 20 to the new array `newArr` at the index position `arr.length + 1`. Because `arr.length` corresponds to the end of the new array, `arr.length + 1` corresponds to the penultimate position of the new array.

3. `newArr[arr.length + 2] = 30;`: Finally, this line of code adds the value 30 to the new array `newArr` at index `arr.length + 2`. Because `arr.length` corresponds to the end of the new array, `arr.length + 2` corresponds to the third to last position of the new array.

In summary, these three lines of code add a new integer value to the end of a new array `newArr` by using the array's index, which is calculated based on the length of the original array `arr` and the length of the new array. In this way, we have successfully added three new values ​​to the new array.

Question 9: Reduction of Arrays

Case: reduction of array:

Existing array int[] arr={1,2,3,4,5,6,7}. Now we need to delete the element with index 4 in the array.

code

package com.atguigu4.search_sort.exer1;


public class ArrayExer01_2 {
    public static void main(String[] args) {
        int[] arr={1,2,3,4,5,6,7};

        int deleteIndex = 4;

        //方式1:不新建数组
//        for(int i = deleteIndex;i < arr.length - 1;i++){
//            arr[i] = arr[i + 1];
//        }
//
//        //修改最后元素,设置为默认值
//        arr[arr.length - 1] = 0;


        //方式2:新建数组,新的数组的长度比原有数组的长度少1个
        int[] newArr = new int[arr.length - 1];
        for (int i = 0; i < deleteIndex; i++) {
            newArr[i] = arr[i];
        }

        for(int i = deleteIndex;i < arr.length - 1;i++){
            newArr[i] = arr[i + 1];
        }

        arr = newArr;

        //遍历arr数组
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + "\t");
        }

    }
}

operation result;

method one;

Way 2:

Code explanation

The above code is a Java program that demonstrates how to delete the element at a specified index position from an integer array. This program uses two different methods to achieve this goal and iterates over the updated array after removing elements. The code is explained below:

1. First, declare a Java class named `ArrayExer01_2`.

2. In the `main` method, an integer array `arr` is created, which contains a set of integers.

3. An integer variable `deleteIndex` is defined, which represents the index position of the element to be deleted, here it is set to `4`.

4. Then, the program shows two different ways to delete the element at the specified index position from the array `arr`:

   a. **Method 1 (commented out part)**: In this method, the program uses a loop to move the elements in the array, move the elements after the element to be deleted one position forward, and then move the last The element is set to the default value `0` to occupy the position. This simulates the effect of deleting an element. But it should be noted that this method modifies the original array `arr`, so if you need to retain the original array, you need to create a backup before the delete operation.

   b. **Method 2**: In this method, the program creates a new integer array `newArr`, whose length is 1 less than the original array `arr`, used to store the result of deleting elements. The program then uses two loops to populate `newArr`, the first loop copies the elements before the deleted element into `newArr`, and the second loop copies the elements after the deleted element into `newArr`. Finally, the program points the `arr` reference to the new array `newArr`, thereby achieving the effect of deleting elements.

5. Finally, the program traverses the `arr` array through a loop and prints out the array contents after removing the elements.

In summary, this code demonstrates how to delete an element at a specified index position from an array, and provides two different implementations. Method 1 modifies the original array, and method 2 creates a new array to store the result of deleting elements. Way 2 is safer as it does not change the original array, but requires additional memory to store the new array.

Detailed explanation of method 1

Method 1 uses a loop to delete the element at the specified index position in the array and modifies the original array. Each step of method 1 is explained in detail below:

1. First, an integer variable `deleteIndex` is defined, indicating the index position of the element to be deleted. Here it is set to `4`, which means that the element with index 4 in the array `arr` is to be deleted (the array index starts counting from 0 ).

2. Next, use a `for` loop to iterate over the array `arr`. The starting condition of the loop is that `i` is equal to `deleteIndex`, that is, starting from the position of the element to be deleted.

3. In the loop, the following operations are performed:
   
   - `arr[i] = arr[i + 1];`: This line of code sets the element at the current position `i` to the next position `i + 1` The value of the element. Through this line of code, the element at the current position is overwritten by the element at the next position, which is equivalent to moving the latter element forward one position.

4. The loop continues, with `i` incremented, until the loop ends. At this time, the elements in the entire array have moved forward one position, covering the element to be deleted.

5. Finally, in order to ensure that the array length remains unchanged, you need to modify the last element and set it to the default value `0` or other appropriate value. This is because the previous loop moved the last element to the penultimate position, but the length of the original array remains unchanged, so the element at the last position needs to be set to the default value.

In summary, method one loops through the array, starting from the position of the element to be deleted, and moving each element forward by one position until the element is deleted. The last position needs to be set to the default value to keep the array length unchanged. . This method will modify the original array `arr`, so use it with caution, especially when you need to retain the original array.

Detailed explanation of method 2

Method 2 uses a new array `newArr` to store the result of deleting the element at the specified index position, without modifying the original array `arr`. The following is a detailed explanation of method two:

1. Create an integer array `newArr` whose length is 1 less than the original array `arr` to store the result of deleting elements.

2. Use a `for` loop to traverse the elements of the `arr` array. The condition of the loop is `i < deleteIndex`, that is, before traversing to the position where the element is to be deleted.

   - In the loop, copy the elements in the `arr` array to the same position in `newArr`. This is because the elements before the deleted element are not affected and can be copied directly to the new array.

3. After the first loop ends, `newArr` already contains all the elements before the element to be deleted.

4. Use another `for` loop to continue traversing the elements of the `arr` array. The conditions of the loop are `i >= deleteIndex` and `i < arr.length - 1`. This is to traverse the elements after the elements to be deleted. element.

   - In this loop, copy the elements in the `arr` array to the previous position in `newArr`, that is, move the elements after the element to be deleted one position forward.

5. After the second loop ends, `newArr` already contains all elements except the element to be deleted, and these elements are arranged in the original order.

6. Finally, point the `arr` reference to the new array `newArr`, so that the original array `arr` points to the new array after deleting the element.

7. Finally, traverse the new array `arr` through a loop and print out the contents of the array after deleting the elements.

In summary, method 2 creates a new array `newArr` to store the result of deleting elements without modifying the original array `arr`. It is processed in two loops, the first loop copies the elements before the deleted element, the second loop copies the elements after the deleted element, and then implements the deletion operation by modifying the array reference to point the original array to the new array. This method preserves the integrity of the original array and is a safer approach.

Question 10: Linear search

Case 1: Linear search

Define the array: int[] arr1 = new int[]{34,54,3,2,65,7,34,5,76,34,67};
Find whether element 5 appears in the above array? If present, output the corresponding index value.

code

package com.atguigu4.search_sort.exer2;


public class LinearSearchTest {
    public static void main(String[] args) {

        int[] arr1 = new int[]{34,54,3,2,65,7,34,5,76,34,67};

        int target = 5;
//        target = 15;

        //查找方式:线性查找
        //方式1:
//        boolean isFlag = true;
//        for(int i = 0;i < arr1.length;i++){
//            if(target == arr1[i]){
//                System.out.println("找到了" + target + ",对应的位置为:" + i);
//                isFlag = false;
//                break;
//            }
//        }
//
//        if(isFlag){
//            System.out.println("不好意思,没有找到此元素");
//        }

        //方式2:
        int i = 0;
        for(;i < arr1.length;i++){
            if(target == arr1[i]){
                System.out.println("找到了" + target + ",对应的位置为:" + i);
                break;
            }

        }

        if(i == arr1.length){
            System.out.println("不好意思,没有找到此元素");
        }


    }
}

Code explanation

This code is a Java program that implements the Linear Search algorithm to find the position of a target value in an integer array. Here is a detailed explanation of the code:

1. Import package: `package com.atguigu4.search_sort.exer2;` at the beginning of the code specifies the package to which this class belongs.

2. Main method (`public static void main(String[] args)`): This is the entry point of the program, and code execution starts from here.

3. Create an integer array (`int[] arr1 = new int[]{34,54,3,2,65,7,34,5,76,34,67};`): An array named `arr1` is an integer array containing some integer values.

4. Set the target value (`int target = 5;`): An integer variable named `target` is defined here, which represents the target value to be found. In the current code, the target value is set to 5, but it can be set to other integers for different lookups.

5. Use the linear search method to find the target value:
   - Method 1: This part of the code is commented out, but it is a typical linear search method. It uses a boolean variable `isFlag` to track whether the target value is found. Then, iterate through the integer array `arr1` through a `for` loop, checking whether each element is equal to the target value. If the target value is found, its position is printed, `isFlag` is set to `false`, and the `break` statement is used to exit the loop. If `isFlag` is still `true` after traversing the entire array, it means that the target value was not found.
   
   - Method 2: This part of the code is the actual linear search method. It uses an integer variable `i` to represent the position of the target value. Iterate through the integer array `arr1` through a `for` loop, checking whether each element is equal to the target value. If the target value is found, its position is printed and the loop is exited using the `break` statement. If `i` is equal to the length of the array after traversing the entire array (`i == arr1.length`), it means that the target value is not found.

In summary, this code demonstrates how to use a linear search algorithm to find a target value in an integer array and output a corresponding message based on the search result. Method 1 and Method 2 are two different implementation methods. Method 2 is more concise, but Method 1 is also an effective linear search method.

Method 1 explained in detail

When you run method one, it uses a boolean variable called `isFlag` to track whether the target value is found. The following is a detailed explanation of method 1:

```java
// Method 1:
boolean isFlag = true; // Initialize a Boolean variable isFlag to true, indicating that the target value has not been found in the initial state
for (int i = 0; i < arr1.length; i++) { / / Use a for loop to traverse the integer array arr1
    if (target == arr1[i]) { // If the target value is equal to the current array element
        System.out.println("Found " + target + ", the corresponding position is: " + i); // Print out the location where the target value is found
        isFlag = false; // Set isFlag to false, indicating that the target value has been found
        break; // Exit the for loop because the target value has been found
    }
}

if (isFlag) { // If isFlag is still true, it means that the target value was not found
    System.out.println("Sorry, this element was not found");
}
```

This is the execution process of method 1:

1. Initialize a Boolean variable `isFlag` to `true`, indicating that the target value has not been found in the initial state.

2. Use a `for` loop to traverse the integer array `arr1`, traversing from index 0 to the last element of the array. In each round of the loop, it checks whether the current array element is equal to the target value `target`.

3. If the target value is found, do the following:
   - Print out a message indicating that the target value was found and its location.
   - Set `isFlag` to `false` to indicate that the target value has been found.
   - Use the `break` statement to exit the `for` loop because there is no need to continue searching.

4. After the `for` loop ends, check the value of `isFlag`. If `isFlag` is still `true`, it means that the target value was not found in the entire array, so a message is printed indicating that this element was not found.

In short, method one tracks the status of the search by setting a Boolean variable `isFlag`. If the target value is found, set `isFlag` to `false`. If `isFlag` is still `true` after the loop ends, it means Target value not found. This is a typical linear search implementation, but the second method is more concise.

Method 2 explained in detail

The second method is to use an integer variable `i` to represent the position of the target value, and use a `for` loop to traverse the integer array `arr1` to find the position of the target value. The following is a detailed explanation of method two:

```java
// Method 2:
int i = 0; // Initialize an integer variable i to 0, used to represent the position of the target value
for (; i < arr1.length; i++) { // Use a for loop to traverse the integer Array arr1
    if (target == arr1[i]) { // If the target value is equal to the current array element
        System.out.println("Found " + target + ", the corresponding position is: " + i); // Print Break where the target value is found
        ; //Exit the for loop because the target value has been found
    }
}

if (i == arr1.length) { // If i is equal to the length of the array, it means that the target value is not found in the entire array
    System.out.println("Sorry, this element was not found");
}
```

This is the execution process of method two:

1. Initialize an integer variable `i` to 0, which is used to represent the position of the target value.

2. Use a `for` loop to traverse the integer array `arr1`, traversing from index 0 to the last element of the array. In each round of the loop, it checks whether the current array element is equal to the target value `target`.

3. If the target value is found, do the following:
   - Print out a message indicating that the target value was found and its location.
   - Use the `break` statement to exit the `for` loop because there is no need to continue searching.

4. After the `for` loop ends, check the value of `i`. If `i` is equal to the length of the array, it means that the target value was not found in the entire array, so a message is printed indicating that this element was not found.

The advantage of the second method is that the code is more concise and does not require additional Boolean variables to track the status of the search. It determines whether the target value is found by checking whether `i` is equal to the length of the array. If `i` is still equal to the length of the array after the loop ends, it means that the target value was not found. This way is more compact and readable.

Question 11: Binary search

Code:

package com.atguigu4.search_sort.exer2;


public class BinarySearchTest {
    public static void main(String[] args) {

        int[] arr2 = new int[]{2,4,5,8,12,15,19,26,37,49,51,66,89,100};

        int target = 5;
//        target = 17;

        int head = 0;//默认的首索引
        int end = arr2.length - 1;//默认的尾索引


        boolean isFlag = false;//判断是否找到了指定元素

        while(head <= end){

            int middle = (head + end) / 2;

            if(target == arr2[middle]){
                System.out.println("找到了" + target + ",对应的位置为:" + middle);
                isFlag = true;
                break;
            }else if(target > arr2[middle]){
                head = middle + 1;
            }else{//target < arr2[middle]
                end = middle - 1;
            }
        }

        if(!isFlag){
            System.out.println("不好意思,未找到");
        }
    }
}

Code explanation:

This code is a Java program that uses the binary search algorithm to find a specific target element in an ordered array of integers. Here's a detailed explanation of the code:

1. First, a Java class named `BinarySearchTest` is defined, which contains the `main` method, which is the entry point of the program.

2. In the `main` method, a sorted integer array `arr2` is created, which contains some pre-sorted integers.

3. An integer variable `target` is defined to store the value of the target element to be found. In this code, `target` is initialized to 5, indicating that the element with value 5 is to be found.

4. Next, two integer variables `head` and `end` are defined, which represent the starting index and ending index of the search range respectively. Initially, `head` is set to 0, indicating the beginning of the search range, and `end` is set to the index of the last element of the array `arr2`, indicating the end of the search range.

5. Created a Boolean variable `isFlag` to mark whether the target element is found. Initially, `isFlag` is set to `false`, indicating that the target element has not been found yet.

6. Enter a `while` loop, the condition is that `head` is less than or equal to `end`, that is, the search range is not reduced to an empty range. The loop will terminate when the target element is found or determined not to exist.

7. Inside the loop, calculate the index of the middle element and store it in the `middle` variable. This is done by adding `head` and `end` and then dividing by 2 to get the index of the middle position.

8. Next, determine the next search direction by comparing the target element `target` with the element at the `middle` position in the array `arr2`.
   - If `target` is equal to `arr2[middle]`, it means that the target element has been found, the program will output the corresponding message and set `isFlag` to `true`, and then exit the loop.
   - If `target` is greater than `arr2[middle]`, it means that the target element is located in the right half of the current search range, so update `head` to `middle + 1` to narrow the search range.
   - If `target` is less than `arr2[middle]`, it means that the target element is in the left half of the current search range, so update `end` to `middle - 1` to narrow the search range.

9. If the target element is still not found after the loop ends (that is, `isFlag` is still `false`), a not found message is output.

In summary, this code implements the binary search algorithm for finding a specific target element in a sorted array of integers. If the target element is found, it prints the position of the target element, otherwise it prints a not found message. The time complexity of this algorithm is O(log n), where n is the size of the array, since it halve the search range in each iteration.

operation result:

Question 12: Maximum subsequence sum of array

Question 13: Poker cards

Question 14: Inverted numbers

Question 15: Traverse the English letters in forward and reverse order

Sixteenth: Determine whether the word is a palindrome word

Question 17: Looking for Koi

 
 

Guess you like

Origin blog.csdn.net/m0_59281987/article/details/133073075