Basic Java learning - Chapter 3 array

Posted by SwiftlyTilting on Wed, 09 Mar 2022 12:55:05 +0100

Basic Java learning - Chapter 3 array

1, Overview of arrays

1. Definition of array

An Array is a collection of multiple data of the same type arranged in a certain order, named with a name, and managed uniformly by numbering.

2. Array related concepts

  1. Array name
  2. Subscript (index)
  3. element
  4. Length of the array (number of elements)

3. Characteristics of array

  1. The array is = = ordered = = arranged
  2. Array belongs to = = reference type variable==
  3. The elements in the array can be either basic data types or reference data types (such as String, array...)
  4. Creating an array object will open up a whole block = = continuous = = space in memory
  5. Once the length of the array is determined, it cannot be modified (the length is immutable)

4. Array classification

  1. According to dimension: one-dimensional array, two-dimensional array
  2. According to the type of array elements: array of basic data type elements and array of reference data type elements

2, One dimensional array

  1. Declaration and initialization of one-dimensional array
  2. How to call an element at a specified position (index) of an array
  3. How to get the length of an array
  4. How to traverse an array
  5. Default initialization value of array elements
  6. Memory parsing of array

1. Declaration and initialization of one-dimensional array

public class Day06_ArrayTest {
    public static void main(String[] args) {
        //1. Declaration and initialization of one-dimensional array
        //Note: once the array is initialized, its length is determined
        int[] ids; //statement
        //1.1 static initialization: the initialization of array and the assignment of array elements are carried out at the same time
        ids = new int[]{1001, 1002, 1003, 1004};
        //It's also right
        // ids = {1001, 1002, 1003, 1004};
        //2.2 dynamic initialization: the initialization of array and the assignment of array elements are carried out separately
        //Here, only the array is initialized (initializing the data type of the elements in the array and the length of the array), but the elements in the array have not been assigned a value
        String[] names = new String[3];

        //Note: in the following two ways, 1 is correct (static initialization) and 2 is wrong
        int[] array = new int[]{1001, 1002, 1003, 1004};
        //int[] array = new int[5]{1001, 1002, 1003, 1004};
    }
}

2. How to call the element at the specified position (index) of the array

public class Day06_ArrayTest {
    public static void main(String[] args) {
        String[] names = new String[3];
		//2. How to call the element at the specified position (index) of the array
        //The index of the array starts at 0 and ends at - 1
        //Assign values to the elements in the array
        names[0] = "Zhang San";
        names[1] = "Li Si";
        names[2] = "Wang Wu";
    }
}

How to get the length of an array

public class Day06_ArrayTest {
    public static void main(String[] args) {
        String[] names = new String[3];
		//3. How to get the length of the array
        //Attribute: length
        System.out.println(names.length);
    }
}

4. How to traverse an array

public class Day06_ArrayTest {
    public static void main(String[] args) {
        String[] names = new String[3];
        names[0] = "Zhang San";
        names[1] = "Li Si";
        names[2] = "Wang Wu";
		//4. How to traverse an array
        for (int i = 0; i < names.length; i++) {
            System.out.println(names[i]);
        }
    }
}

5. Default initialization value of array element

1) Array elements are the default initialization values of integers (byte, short, int, long): 0
public class Day06_ArrayTest {
    public static void main(String[] args) {
        //Array elements are of type int
        int[] arr1 = new int[4];
        for (int i = 0; i < arr1.length; i++) {
            System.out.println(arr1[i]);
        }
        //Array elements are of type short
        short[] arr2 = new short[4];
        for (int i = 0; i < arr2.length; i++) {
            System.out.println(arr2[i]);
        }
    }
}
2) Array elements are floating-point types (float, double). The default initialization value is 0.0
public class Day06_ArrayTest {
    public static void main(String[] args) {
        //Array elements are of type double
        double[] arr3 = new double[4];
        for (int i = 0; i < arr1.length; i++) {
            System.out.println(arr3[i]);
        }
    }
}
3) The array element is the default initialization value of char type: 0 or '\ u0000' (it means that the character with ASCII code of 0 is null, not the character '0')
public class Day06_ArrayTest {
    public static void main(String[] args) {
        //Array elements are of type char
        char[] arr4 = new char[4];
        for (int i = 0; i < arr1.length; i++) {
            System.out.println(arr4[i]);
        }
    }
}
4) The array element is the default initialization value of boolean type: false
public class Day06_ArrayTest {
    public static void main(String[] args) {
        //Array elements are of type boolean
        boolean[] arr5 = new boolean[4];
        for (int i = 0; i < arr1.length; i++) {
            System.out.println(arr5[i]);
        }
    }
}
5) Array element is the default initialization value of reference data type (such as String, array, etc.): null
public class Day06_ArrayTest {
    public static void main(String[] args) {
        //The array element is string (reference data type)
        String[] arr6 = new String[4];
        for (int i = 0; i < arr1.length; i++) {
            System.out.println(arr6[i]);
        }
    }
}

6. Memory parsing of array

Heap and stack in Java

Java divides memory into two types: stack memory and heap memory. Stack and heap are places where Java stores data in Ram. Unlike C + +, Java automatically manages stacks and heaps, and programmers cannot directly set stacks or heaps.

  • Some local variables defined inside the method (function), including = = basic data type variables (int, short, long, byte, float, double, boolean, char) and reference data type variables of array or object (such as array1) = = are allocated in the stack memory of the function. When a variable is defined in a code block, Java allocates memory space for the variable in the stack. When the scope of the variable is exceeded, Java will automatically release the memory space allocated for the variable, which can be used for other purposes immediately.
  • Heap memory is used to store objects and arrays created by new. The memory allocated in the heap is managed by the automatic garbage collector of the Java virtual machine. After an array or object is generated in the heap, a special variable can be defined in the stack so that the value of this variable in the stack is equal to the first address of the array or object in the heap memory. This variable in the stack becomes the = = reference data type variable of the array or object = =. The reference type variable is equivalent to a name for the array or object. Later, the reference type variable in the stack can be used in the program to access the array or object in the heap (similar to a pointer).

The Java heap is a runtime data area, Class (objects allocate space from them. These objects are established through new, newarray, anewarray, multianewarray and other instructions, and they do not need program code to explicitly release. Heap is responsible for garbage collection. The advantage of heap is that it can dynamically allocate memory size, and the lifetime does not need to tell the compiler in advance, because it dynamically allocates memory at runtime, Java garbage collection The collector will automatically collect the data that is no longer used. However, the disadvantage is that the access speed is slow due to the dynamic allocation of memory at run time.

The advantage of stack is that the access speed is faster than heap, second only to register, and stack data can be shared. However, the disadvantage is that the data size and lifetime in the stack must be determined and lack of flexibility. The stack mainly stores some basic types of variables (, int, short, long, byte, float, double, boolean, char) and object handles.



Note: String is actually stored in the String constant pool in the method area. The value of a reference type variable is either null or address

7. Example of one-dimensional array

Example 1: read students' scores from the keyboard, find out the highest score, and output the grades of students' scores

  • >=The highest score is - 10 and the grade is A
  • >=Highest score - 20 grade B
  • >=The highest score is - 30 and the grade is C
  • Other grades are D
    Tip: first read in the number of students, create an int array according to the number of students, and store the student scores
import java.util.Scanner;
public class Day06_ArrayExer {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter the number of students:");
        //1. Number of students obtained
        int StudentNum = scan.nextInt();
        //2. Create an int array according to the number of students to store student scores
        int[] scoreArr = new int[StudentNum];
        System.out.println("Please enter" + StudentNum +  "Results:");
        //3. Obtain student scores from the keyboard in turn and store them in the array, and find the maximum value by the way
        int maxsocre = scoreArr[0];
        for (int i = 0; i < scoreArr.length; i++) {
            scoreArr[i] = scan.nextInt();
            if (scoreArr[i] > maxsocre) {
                maxsocre = scoreArr[i];
            }
        }
        //4. According to the difference between each student's score and the highest score, get the grade of each student and output the grade
        for (int i = 0; i < scoreArr.length; i++) {
            char level;
            if (scoreArr[i] >= maxsocre - 10) {
                level = 'A';
            } else if (scoreArr[i] >= maxsocre - 20) {
                level = 'B';
            } else if (scoreArr[i] >= maxsocre - 30) {
                level = 'C';
            } else {
                level = 'D';
            }
            System.out.println("The first" + (i + 1) + "The grades of students are:" + level);
        }
    }
}

3, Two dimensional array

  • Two dimensional array can be understood as = = one-dimensional array array1 exists as the element = = of another one-dimensional array array2.
  • From the perspective of the underlying operating mechanism of the array, there is no multidimensional array
  • A two-dimensional array can be regarded as a table. The number of rows is equal to the length of the outer array and the number of columns is equal to the length of the inner array
  1. Declaration and initialization of two-dimensional array
  2. How to call an element at a specified position (index) of an array
  3. How to get the length of an array
  4. How to traverse an array
  5. Default initialization value of array elements
  6. Memory parsing of array

1. Declaration and initialization of two-dimensional array

public class Day06_twoDArrayTest {
    public static void main(String[] args) {
        //1. Declaration and initialization of two-dimensional array
        //1.1 static initialization
        int[][] arr1 = new int[][]{{1, 2, 3}, {4, 5}, {6, 7, 8}}; //The length of the inner array can be different
        //It's also right
        // int[][] arr1 = {{1, 2, 3}, {4, 5}, {6, 7, 8}};
        //1.2 dynamic initialization mode I
        //The length of the outer one-dimensional array is 3 and the length of each inner one-dimensional array is 2
        int[][] arr2 = new int[3][2];
        //Dynamic initialization mode 2
        int[][] arr3 = new int[3][];
    }
}

2. How to call the element at the specified position (index) of the array

public class Day06_twoDArrayTest {
    public static void main(String[] args) {
        int[][] arr1 = new int[][]{{1, 2, 3}, {4, 5}, {6, 7, 8}};
        int[][] arr2 = new int[3][2];
        int[][] arr3 = new int[3][];
        //2. How to call the element at the specified position (index) of the array
        System.out.println(arr1[0][1]);
        System.out.println(arr2[0][1]);
        //Initialize a one-dimensional array with a length of 3 at the 0th position of the outer array of arr3
        arr3[1] = new int[3];
        System.out.println(arr3[1][0]); //0
    }
}

How to get the length of an array

public class Day06_twoDArrayTest {
    public static void main(String[] args) {
        int[][] arr1 = new int[][]{{1, 2, 3}, {4, 5}, {6, 7, 8}};
        //How to get the length of an array
        System.out.println(arr1.length); //3 returns the length of the outer array
        System.out.println(arr1[1].length); //2 returns the length of the inner array at the first position of the outer array
    }
}

4. How to traverse an array

public class Day06_twoDArrayTest {
    public static void main(String[] args) {
        int[][] arr1 = new int[][]{{1, 2, 3}, {4, 5}, {6, 7, 8}};
        //4. How to traverse an array
        for (int i = 0; i < arr1.length; i++) {
            for (int j = 0; j < arr1[i].length; j++) {
                System.out.print(arr1[i][j] + " ");
            }
            System.out.println();
        }
    }
}

5. Default initialization value of array element

Regulation: the two-dimensional array is divided into the elements of the outer array and the elements of the memory array. as

int[][] arr = new int[4][3];
//Outer elements: arr[0], arr[1], etc
//Inner elements: arr[0][0], arr[0][1], etc
  1. For dynamic initialization mode 1
  • The initialization value of the outer element is the first address value
  • The initialization value of the inner element is: the same as that of the one-dimensional array
  1. For dynamic initialization mode 2
  • The initialization value of the outer element is null (because = = the element of the outer array is a reference data type (array), and the initialization value is null = =)
  • The initialization value of the inner element is: it cannot be called, otherwise an error will be reported
    Special note: the value of the outer array element can only be null or address value, because the element of the outer array is an array (reference data type variable), and the value of the reference data type variable is either null or address value
public class Day06_ArrayTest {
    public static void main(String[] args) {
        //5. Default initialization value of array element
        //Dynamic initialization mode 1
        int[][] arr = new int[4][3];
        System.out.println(arr[0]); //The address value of the inner array at position 0 of the outer array
        System.out.println(arr[0][0]); //0
        
		//Dynamic initialization mode 2
        int[][] arr1 = new int[4][];
        System.out.println(arr1[0]); //null
        //System.out.println(arr1[0][0]); // report errors
    }
}

6. Memory parsing of array

7. Example of two-dimensional array

Example 1: get the sum of all elements in the arr array

public class twoDArrayExer {
    public static void main(String[] args) {
        int[][] arr = new int[][]{{3, 5, 8}, {12, 9}, {7, 0, 6, 4}};
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
             for (int j = 0; j < arr[i].length; j++) {
                 sum += arr[i][j];
             }
        }
        System.out.println(sum);
    }
}

Example 2: Declaration

int[] x,y[] //x is a one-dimensional array and y is a two-dimensional array

The following options allow compilation:

a) x[0] = y;
b) y[0] = x; √
c) y[0][0] = x; 
d) x[0][0] = y;
e) y[0][0] = x[0]; √
f) x = y;
//Tips:
1. Correct declaration of one-dimensional array: int[] x or int x[]
2. Correct declaration of two-dimensional array: int[][] y or int[] y[] or int y[][]

4, Common algorithms for arrays

  1. Assignment of array elements (Yang Hui triangle, number of loops)
  2. Find the maximum, minimum, average, sum, etc. of elements in a numeric array
  3. Copy, inversion and search of array (linear search and dichotomy search)
  4. Sorting algorithm of array elements (bubble sort, quick sort)

1. Assignment of array elements (Yang Hui's triangle and shape return number)

Exercise 1: print a 10 Line Yang Hui triangle using a two-dimensional array

  1. The first line has one element and the nth line has n elements
  2. The first and last elements of each line are 1
  3. Starting from the third line, for elements other than the first and last, the
yanghui[i][j] = yanghui[i-1][j-1] + yanghui[i-1][j];
public class twoDArrayExer {
    public static void main(String[] args) {
        int[][] yanghui = new int[10][];
        for (int i = 0; i < yanghui.length; i++) {
            //The first line has one element and the nth line has n elements
            yanghui[i] = new int[i + 1];
            //Assign values to the first and last elements of each line (continuous assignment)
            yanghui[i][0] = yanghui[i][i] = 1;
        }
        //Starting from the third line, assign values to elements other than the first and last
        for (int i = 2; i < yanghui.length; i++) {
            for (int j = 1; j < yanghui[i].length - 1; j++) {
                yanghui[i][j] = yanghui[i-1][j-1] + yanghui[i-1][j];
            }
        }
        //Loop traversal output
        for (int i = 0; i < yanghui.length; i++) {
            for (int j =0; j < yanghui[i].length; j++) {
                System.out.print(yanghui[i][j] + " ");
            }
            System.out.println();
        }
    }
}

After optimization: A for loop nesting is removed

public class twoDArrayExer {
    public static void main(String[] args) {
        int[][] yanghui = new int[10][];
        for (int i = 0; i < yanghui.length; i++) {
            //The first line has one element and the nth line has n elements
            yanghui[i] = new int[i + 1];
            //The first and last elements of each line are 1 (continuous assignment)
            yanghui[i][0] = yanghui[i][i] = 1;
            //Assign values to the first and last elements at the beginning of the third line (if is not required, because the loop condition of the for loop is false when i=0 or 1)
            for (int j = 1; j < yanghui[i].length - 1; j++) {
            	yanghui[i][j] = yanghui[i-1][j-1] + yanghui[i-1][j];
            }
        }
        //Loop traversal output
        for (int i = 0; i < yanghui.length; i++) {
            for (int j =0; j < yanghui[i].length; j++) {
                System.out.print(yanghui[i][j] + " ");
            }
            System.out.println();
        }
    }
}

2. Find the maximum value, minimum value, average value and sum of elements in the numerical array

Exercise 1: define a one-dimensional array of int type, including 10 elements, assign some random integers respectively, and then find the maximum, minimum and sum values of all elements. Requirement: all random numbers are two digits.

  • How to obtain an integer random number:
(int)(Math.random() * (b - a + 1) + a)
public class Day07_ArrarCommonExer {
    public static void main(String[] args) {
        int[] arr = new int[10]; //Element is initialized to 0 by default
        int max = 0;
        int min = 100;
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            //Assign 10 ~ 99 random numbers
            arr[i] = (int)(Math.random() * (99 - 10 + 1) + 10);
            //Maximum
            if (arr[i] > max) {
                max = arr[i];
            }
            //minimum value
            if (arr[i] < min) {
                min = arr[i];
            }
            //Sum value
            sum += arr[i];
        }
        System.out.print("10 The elements are:");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
        System.out.println("The maximum value is:" + max);
        System.out.println("The minimum value is:" + min);
        System.out.println("And values are:" + sum);
    }
}

3. Copy, reverse and search of array (linear search and dichotomy search)

1) Distinction: assignment of array variables and copying of arrays
  1. Create a class named ARRAYTEST, and then declare array1, array2 and array3 int arrays in the main() method
  2. Using braces {}, initialize array1 to 8 prime numbers: 2, 3, 5, 7, 11, 13, 17, 19
  3. Print the contents of the original array1
  4. Realize the replication of array2 to array1
  5. The assigned array3 variable is equal to array1, and the modified even index element in array3 is equal to the corresponding index value
  6. Print three array1, array2, array3
public class Day07_ArrarSetValueExer {
    public static void main(String[] args) {
       int[] array1, array2, array3;
        array1 = new int[]{2, 3, 5, 7, 11, 13, 17, 19};
        System.out.print("original array1: ");
        for (int i = 0; i < array1.length; i++) {
            System.out.print(array1[i] + " ");
        }
        System.out.println();
        //Replication of array2 to array1
        array2 = new int[array1.length]; //A new independent array space is opened up for array2 in the heap space by means of new
        for (int i = 0; i < array2.length; i++) {
            array2[i] = array1[i];
        }
        //Assignment of array variables, not copying of arrays
        array3 = array1;
        for (int i = 0; i < array3.length; i++) {
            if (i % 2 == 0) {
                array3[i] = i;
            }
        }
        System.out.print("array1: ");
        for (int i = 0; i < array1.length; i++) {
            System.out.print(array1[i] + " ");
        }
        System.out.println();
        System.out.print("array2: ");
        for (int i = 0; i < array2.length; i++) {
            System.out.print(array2[i] + " ");
        }
        System.out.println();
        System.out.print("array3: ");
        for (int i = 0; i < array3.length; i++) {
            System.out.print(array3[i] + " ");
        }
    }
}

Summary:
7. It can be seen that after operating on the elements in array3, the elements in array1 have also changed, while the elements in array2 are still consistent with those in the original array1
8. array3 = array1; Represents the assignment of array variables (i.e. the assignment of variables referring to data types), rather than the replication of arrays. Specifically, the first address value of the array pointed to by array1 in the stack is assigned to array3. At this time, array3 also points to the array pointed to by array1 in the heap. In other words, the address values saved by the reference type variables array1 and array3 are the same, and they all point to the same array entity in the heap space.
9. Array2 is a copy of array1. The address values saved in the stack are different and point to two independent array entities in the heap. Therefore, the operation on the elements in array3 does not affect the elements in array2

2) Inversion of array

For array String[] arr = new String [] {"A", "B", "C", "D", "E", "F"}; Reverse

public class Day07_ArrarSetValueExer {
    public static void main(String[] args) {
    	String[] arr = new String[]{"AA", "BB", "CC", "DD", "EE", "FF"};
        //Method 1: exchange variable values with corresponding position elements
        for (int i = 0; i < arr.length / 2; i++) {
            String temp = arr[i];
            arr[i] = arr[arr.length - 1 - i];
            arr[arr.length - 1 - i] = temp;
        }
        for (int i = 0; i< arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();

        //Method 2: use i and j to represent the head and tail elements respectively
        for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
            String temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
        for (int i = 0; i< arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
3) Array lookup (search)
a) Linear search
  • Directly find one by one, and stop when you find it
public class Day07_ArrarSetValueExer {
    public static void main(String[] args) {
    	//Linear search
        boolean flag = true;
        for (int i = 0; i < arr.length; i++) {
            //if (arr[i] == dest) {
            if (dest.equals(arr[i])) {
                System.out.println("BB stay arr The index in is:" + i);
                flag = false;
                break;
            }
        }
        if (flag) {
            System.out.println("arr Element does not exist in BB");
        }
    }
}
b) Dichotomy search
  • Premise: the array to be searched must be orderly
public class Day07_ArrarSetValueExer {
    public static void main(String[] args) {
    	int[] arr2 = new int[]{2, 5, 7, 8, 10, 15, 18, 20, 22, 25, 28};
        int dest1 = 18;
        //Used to identify whether the target is found
        boolean isFlag = true;
        //The first index of the search range, initially 0
        int start = 0;
        //The last index of the search range, initially the index of the last element of the array
        int end = arr2.length - 1;
        //binary search 
        while (start <= end) { //Note that the equal sign should be added here, because there may be only one number left in the final search range, so you still need to search again
            //The index of the middle element of the search range. If there are even elements in the search range, the middle element on the left is taken
            int mid = (start + end) / 2;
            //Compare the number of all lookups and the size of the intermediate element value to adjust the search range
            //If the number to be searched is less than the value of the intermediate element, it means that the number to be searched is on the left side of the intermediate element, and end is set to the previous index of mid
            if (dest1 < arr2[mid]) {
                end = mid - 1;
            //If the number to be searched > intermediate element value, it means that the number to be searched is on the right side of the intermediate element. Set start to the index after mid
            } else if (dest1 > arr2[mid]) {
                start = mid + 1;
            //If the number of all searches = = intermediate element value, the search ends
            } else {
                System.out.println("The index of this element in the array is" + mid);
                isFlag = false;
                break;
            }
        }
        if (isFlag) {
            System.out.println("The element does not exist in the array");
        }
    }
}

4. Sorting algorithm of array elements (bubble sorting and quick sorting)

1, Top ten internal sorting algorithms:

  • Select sort
  1. Direct selection sorting
  2. Heap sorting (can say the implementation idea)
  • Exchange sort
  1. Bubble sorting (skilled hand tearing)
  2. Quick sorting (if you can say the realization idea, you'd better be able to tear it by hand)
  • Insert sort
  1. Direct insert sort
  2. Binary Insertion Sort
  3. Shell sort
  • Merge and sort (be able to say the realization idea)

  • Bucket sort

  • Cardinality sort

**2, Indicators to measure sorting algorithm: * * time complexity, space complexity and stability

**3, Time complexity of different sorting algorithms: * * focus on bubble sorting and quick sorting

1) Bubble sorting
  • Sorting ideas (sorted from small to large):
  1. Compare the size of adjacent elements in the array from front to back. If it is found that the order is reverse, exchange it to maximize the sorting code of the last element (the first round of sorting)
  2. Repeat step 1 for all elements except the last element, so that the next largest value elements are also ranked last (the second round of sorting)
  3. Continue to repeat step 1 for fewer and fewer elements each time, so that the elements with larger sorting code gradually move back from the beginning until there is no pair of elements to compare, and the sorting ends (total = = arr.length - 1 = = round sorting)
public class Day07_BubbleSortTest {
    public static void main(String[] args) {
        int[] arr = new int[]{43, 32, 76, -98, 0, 64, 33, -21, 32, 99};
        //Total arr.length - 1 round of sorting
        for (int i = 0; i < arr.length - 1; i++) {
            //Compare the size of adjacent elements in the array from front to back, and exchange if it is found in reverse order
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        //Print sorted array
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

It can also be written as

public class Day07_BubbleSortTest {
    public static void main(String[] args) {
        int[] arr = new int[]{43, 32, 76, -98, 0, 64, 33, -21, 32, 99};
        //Total arr.length - 1 round of sorting
        for (int i = arr.length - 1; i > 0; i--) {
            //Compare the size of adjacent elements in the array from front to back, and exchange if it is found in reverse order
            for (int j = 0; j < i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        //Print sorted array
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
2) Quick sort
  • Sorting ideas (sorted from small to large):
  1. Picking out an element from a sequence is called a "pivot"
  2. Partition operation: reorder the sequence. All elements smaller than the benchmark value are placed in front of the benchmark, and all elements larger than the benchmark value are placed behind the benchmark (the same number can be on either side). At the end of this partition, the benchmark is in the middle of the sequence.
  3. Recursively sorts partitions that are smaller than the reference value element and partitions that are larger than the reference value element.
  4. The bottom case of recursion is that the size of the sequence is 0 or 1, that is, it has always been sorted. Although it recurses all the time, the algorithm will always end, because in each iteration, it will put at least one element to its last position.

5, Use of Arrays tool class

==java.util.Arrays = = class is a tool class for manipulating arrays. It contains various methods for manipulating arrays (such as sorting and searching)

1. boolean equals(int[] a,int[] b): judge whether the two arrays are equal (whether the corresponding elements of the two arrays are equal)

import java.util.Arrays;
public class Day07_ArraysClassTest {
    public static void main(String[] args) {
        int[] arr1 = new int[]{1, 2, 3, 4};
        int[] arr2 = new int[]{1, 3, 2, 4};
        //Judge whether the two arrays are equal (whether the corresponding elements of the two arrays are equal)
        boolean isEquals = Arrays.equals(arr1, arr2);
        System.out.println(isEquals); //false
    }
}

2. String toString(int[] a): output array information (each element)

import java.util.Arrays;
public class Day07_ArraysClassTest {
    public static void main(String[] args) {
        int[] arr1 = new int[]{1, 2, 3, 4};
        int[] arr2 = new int[]{1, 3, 2, 4};
        //Output array information (each element)
        System.out.println(Arrays.toString(arr1)); //[1, 2, 3, 4]
    }
}

3. void fill(int[] a,int val): fill the specified value into the array (replace all elements in the array with the specified value)

import java.util.Arrays;
public class Day07_ArraysClassTest {
    public static void main(String[] args) {
        int[] arr1 = new int[]{1, 2, 3, 4};
        int[] arr2 = new int[]{1, 3, 2, 4};
        //Fills the array with the specified value (replaces all elements in the array with the specified value)
        Arrays.fill(arr1, 10);
        System.out.println(Arrays.toString(arr1)); //[10, 10, 10, 10]
    }
}

4. void sort(int[] a): sort the array (from small to large)

  • The bottom layer uses quick sort
import java.util.Arrays;
public class Day07_ArraysClassTest {
    public static void main(String[] args) {
        int[] arr1 = new int[]{1, 2, 3, 4};
        int[] arr2 = new int[]{1, 3, 2, 4};
        //Sort the array (from small to large)
        Arrays.sort(arr2);
        System.out.println(Arrays.toString(arr2)); //[1, 2, 3, 4]
    }
}

5. int binarySearch(int[] a,int key): binary the sorted array to retrieve the specified value

  • Returns the index of the specified value in the array. If the return value is non negative, it is the corresponding index; If the return value is negative, it indicates that it is not found
import java.util.Arrays;
public class Day07_ArraysClassTest {
    public static void main(String[] args) {
        int[] arr1 = new int[]{1, 2, 3, 4};
        int[] arr2 = new int[]{1, 3, 2, 4};
        //Sort the array (from small to large)
        Arrays.sort(arr2);
        System.out.println(Arrays.toString(arr2)); //[1, 2, 3, 4]
        //Binary the sorted array to retrieve the specified value
        int index = Arrays.binarySearch(arr2, 2); //Return index value
        System.out.println(index);
        //If the key does not exist in the array, a negative number is returned
        int index1 = Arrays.binarySearch(arr2, 8);
        System.out.println(index1);
        
        //It can usually be written in this form:
        if (index >= 0) {
            System.out.println(index);
        } else {
            System.out.println("not found");
        }
    }
}

6, Common exceptions to arrays

  • Common exceptions in arrays
  1. Exception for array out of index: ArrayIndexOutOfBoundsException
  2. Null pointer exception: NullPointerException

1. Exception of array exceeding index: ArrayIndexOutOfBoundsException

public class Day07_ArrayException {
    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 3, 4, 5};
        for(int i = 0; i <= arr.length; i++) {
            System.out.println(arr[i]); //ArrayIndexOutOfBoundsException
        }

    }
}

2. Null pointer exception: NullPointerException

public class Day07_ArrayException {
    public static void main(String[] args) {
        //Case 1:
        int[] arr1 = new int[]{1, 2, 3};
        arr1 = null;//Array arr1 is a reference data type variable whose value is either null or address
        System.out.println(arr1[0]); //NullPointerException
        //Case 2:
        int[][] arr2 = new int[3][];
        System.out.println(arr2[0]); //null
        System.out.println(arr2[0][0]); //NullPointerException
        //Case 3:
        String[] arr3 = new String[]{"AA", "BB", "CC"};
        arr3[0] = null;
        System.out.println(arr3[0].toString()); //NullPointerException
    }
}
 for(int i = 0; i <= arr.length; i++) {
            System.out.println(arr[i]); //ArrayIndexOutOfBoundsException
        }

    }
}

2. Null pointer exception: NullPointerException

public class Day07_ArrayException {
    public static void main(String[] args) {
        //Case 1:
        int[] arr1 = new int[]{1, 2, 3};
        arr1 = null;//Array arr1 is a reference data type variable whose value is either null or address
        System.out.println(arr1[0]); //NullPointerException
        //Case 2:
        int[][] arr2 = new int[3][];
        System.out.println(arr2[0]); //null
        System.out.println(arr2[0][0]); //NullPointerException
        //Case 3:
        String[] arr3 = new String[]{"AA", "BB", "CC"};
        arr3[0] = null;
        System.out.println(arr3[0].toString()); //NullPointerException
    }
}

Topics: Java Algorithm