JAVA language syntax_ Array (part4)

Keywords: Java Eclipse JavaSE array

JAVA language syntax

4, Array

1. Overview of arrays
Overview of arrays:
(1),Understanding of arrays: array Array,It 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:
	> Array name
	> element
	> Corner mark, subscript, index
	> The length of the array and the number of elements
(3),Characteristics of array:
	1),Array is a variable of reference data type. The elements of array can be either basic data type or reference data type.
	2),Creating an array object opens up a whole contiguous space in memory.
	3),Once the length of the array is determined, it cannot be modified.
	4),Arrays are ordered.
(4),Classification of arrays:
	①.According to dimension: It can be divided into one-dimensional array, two-dimensional array and three-dimensional array.
	②.According to the element type of the array: An array that can be divided into basic data type and reference type elements
2. Use of one-dimensional arrays
Array discussion learning points:
(1),Declaration and initialization of arrays;
(2),How to call an element at a specified position of an array;
(3),How to get the length of an array;
(4),How to traverse an array;
(5),Default and initial values of array elements;
(6),Memory parsing of arrays.

Code demonstration (for the above 6 learning points):

package com.rucoding.d7;

/**
 * @author LiuYiXin
 *
 */
public class ArrayDemo01 {
	public static void main(String[] args) {

		/*
		 * (1),Declaration and initialization of array; Reference data types: Declaration and initialization of arrays
		 */

		// Review the declaration and initialization of basic data types
		int i1; // Declare variable type
		i1 = 10; // initialization
		int i2 = 10; // Declaration and initialization

		// analogy
		int[] arr; // Array declaration
		// Static initialization: array initialization and array element assignment are performed simultaneously
		arr = new int[] { 1, 2, 3, 4 }; // Initialization: static initialization
		// Dynamic initialization: array initialization and array element assignment are performed separately
		String[] names = new String[5];

		/*
		 * (2),How to call the element at the specified position of the array; The subscript index of the array is called through subscript, subscript and index (a meaning), starting from 0 and ending with the length of the array - 1
		 */
		// names array element for assignment operation
		names[0] = "Zhang San";
		names[1] = "Li Si";
		names[2] = "Wang Wu";
		names[3] = "Zhao Liu";
		names[4] = "pseudo-ginseng";
		// names[5] = "old eight"// If the array exceeds the subscript, it will pass the compilation, but it will fail at run time. java.lang.ArrayIndexOutOfBoundsException

		/*
		 * (3),How to get the length of the array;
		 */
		//Property, not method, length property
		System.out.println(arr.length); //4
		System.out.println(names.length); //5
		
		
		/*
		 * (4),How to traverse an array;
		 */
		//Traverse the array elements and output circularly
		for(int i = 0;i < names.length;i++){
			System.out.println(names[i]);
		}
		
		
		/*
		 * (5),Default and initial values of array elements;
		 * Summary:
		 * 1),The default initialization value for array integers is 0
		 * 2),The default initialization value for floating point is 0.0
		 * 3),The default initialization value for Boolean types is false
		 * 4),char The default initialization value for character types is 0 instead of '0'
		 * 5),The default initialization value of an array of reference data types (such as String type) is null
		 */
		
		//Default initialization value for array
		int[] arrInt = new int[4];
		for(int i = 0;i < arrInt.length;i++){
			System.out.println(arrInt[i]); //The default initialization value of an integer is 0
		}
		
		short[] arrShort = new short[4];
		for(int i = 0;i < arrShort.length;i++){
			System.out.println(arrShort[i]);//The default initialization value of an integer is 0
		}
		
		//float 
		float[] arrFloat = new float[4];
		for(int i = 0;i < arrFloat.length;i++){
			System.out.println(arrFloat[i]);//The default initialization value of floating point is 0.0
		}
		
		//Boolean type
		boolean[] arrBoolean = new boolean[4];
		for(int i = 0;i < arrBoolean.length;i++){
			System.out.println(arrBoolean[i]);//The default initialization value of boolean type is false
		}
		
		//char type
		char[] arrChar = new char[4];
		for(int i = 0;i < arrChar.length;i++){
			System.out.println(arrChar[i]);//The default initialization value of char type is 0 instead of '0'
		}
		//verification
		if(arrChar[0] == 0){
			System.out.println("Hi");
		}
		
		//String type
		String[] arrString = new String[4];
		for(int i = 0;i < arrString.length;i++){
			System.out.println(arrString[i]);//The default initialization value of String type (reference data type) is null
		}
		
		//Verify
		if(arrString[0] == null){
			System.out.println("Rucoding");
		}
		
	}
}

Learning point (6):

(6) Memory parsing of array.

Simplified structure of memory:

2.1 memory parsing of one-dimensional array
Analyze the memory structure diagram of the following code:

int[] arr = new int[]{1,2,3}; //Statically declare an arr array of type int and assign three elements: 1, 2 and 3
String[] arr1 = new String[4]; //Dynamically declare an arr1 array of reference type and initialize the length to 4
arr1[1] = ""Andy Lau";  //Assign a value to an arr array with a dynamic declaration length of 4
arr1[2] = ""Zhang Xueyou"; //Assign a value to an arr array with a dynamic declaration length of 4
arr1 = new String[3]; //Recreate an array that opens up a continuous space and initializes the length of 3 to arr1
System.out.println(arr1[1]);//Null / / the default initialization value of the reference type is null

Memory analysis diagram (general meaning):

As shown in the figure, the memory parsing of the final array is completed, and the internal value of the array is null.

3. Array exercise

Exercise 1: print your mobile phone number by using an array.

package com.rucoding.d7.exer;

/**
 * @author LiuYiXin
 *
 */
public class ArrayPrintTelDemo01 {
	//Print personal mobile phone number 13620167671 through array (randomly generated, do not dial!)
	public static void main(String[] args) {
		//Define an array and statically assign the number of mobile phone numbers
		int[] telNum = new int[]{7,3,6,2,0,6,1};
		//The mobile phone number is 11 digits. Traverse 11 times and take the index value corresponding to the telNum array above to form the mobile phone number
		int[] arr1 = {6,1,2,3,4,6,5,0,5,0,6};
		//Define my number variable
		String myTel = "";	
		for(int i = 0;i < arr1.length;i++){
			myTel += telNum[arr1[i]];
		}
		System.out.print("My contact information:" + myTel);
		
	}
}	

originate:

/*
 * Shengjingfang single room is rented for 4 months, 550 yuan / month (water, electricity and coal pool, network fee of 35 yuan / month), with complete air conditioning, toilet and kitchen.
 * The house is full of people from the IT industry and likes to be quiet. Therefore, it is required that the tenants should preferably be peers or young people who have just graduated, and love to be clean and quiet.
 * eclipse Code one click Format normalization: Ctrl+Shift+F
 */
public class ArrayDemo {
	public static void main(String[] args) {
		int[] arr = new int[] { 8, 2, 1, 0, 3 };
		int[] index = new int[] { 2, 0, 3, 2, 4, 0, 1, 3, 2, 3, 3 };
		String tel = "";
		for (int i = 0; i < index.length; i++) {
			tel += arr[index[i]];
		}
		System.out.println("contact information:" + tel);
	}
}

Exercise 2:

	/*
	 * 2. Read the student's grades from the keyboard, find out the highest score, and output the student's grade. 
	 *  score > = highest score - 10, grade 'A'
	 * Score > = highest score - 20, grade 'B'
	 * Score > = highest score - 30, grade '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.
	 */

Code demonstration:

package com.rucoding.d7.exer;

import java.util.Scanner;

/**
 * @author LiuYiXin
 *
 */
public class ArrayStuScoreDemo02 {
	/*
	 * 2. Read the student's grades from the keyboard, find out the highest score, and output the student's grade.
	 * Score > = highest score - 10, grade 'A'   
	 * Score > = highest score - 20, grade 'B'
	 * Score > = highest score - 30, grade '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.
	 */
	
	public static void main(String[] args) {
		
		//Declare a Scanner class that can receive keyboard input
		Scanner scanner = new Scanner(System.in);
		//At this point, you can create an array and initialize dynamically
		System.out.println("Please enter the number of students:");
		int num = scanner.nextInt();
		int[] stuNum = new int[num];
		//Define a variable with the highest score
		int maxScore = 0;
		
		//Enter student grades
		System.out.println("Please enter" + stuNum.length + "Results:");
		for(int i = 0;i < stuNum.length;i++){
			stuNum[i] = scanner.nextInt();
			//Compare the entered highest scores with the entered scores
			if(maxScore < stuNum[i]){
				maxScore = stuNum[i]; 
			}
		}
		
		//Print highest score
		System.out.println("The highest score is:" + maxScore);
		
		//Define a level of variables
		char level;
		
		//Traverse student scores and judge registration
		for(int i = 0;i < stuNum.length;i++){
			if(maxScore - stuNum[i] <= 10){ //
				level = 'A';
			}else if(maxScore - stuNum[i] <= 20){
				level = 'B';
			}else if(maxScore - stuNum[i] <= 30){
				level = 'C';
			}else{
				level = 'D';
			}
			System.out.println("student " + i + " score is " + stuNum[i] + " grade is " + level);
		}
			
	}
	
}

4. Definition and traversal of two-dimensional array

From the perspective of the underlying operation mechanism, two-dimensional array is also one-dimensional array. This paper analyzes two-dimensional array with six discussion points of one-dimensional array.

Use of two-dimensional arrays:
Format 1(dynamic initialization): int[][] arr = new int[3][2];
Defined a name arr Two dimensional array of
 There are three one-dimensional arrays in the two-dimensional array
 There are 2 elements in each one-dimensional array
 The names of one-dimensional arrays are, arr[0],arr[1],arr[2]
If the subscript of a one-dimensional array 1 is assigned 66, arr[0][1] = 66. 

Format 2(dynamic initialization): int[][] arr = new int[3][];
There are three one-dimensional arrays in the two-dimensional array.
Each one-dimensional array is the default initialization value null (Note that it is different from format 1)
The three one-dimensional arrays can be initialized respectively.
arr[0] = new int[3];
arr[1] = new int[1];
arr[2] = new int[2];

Code demonstration:

package com.rucoding.d7;

/**
 * @author LiuYiXin
 *
 */
public class ArrayDemo02 {
	/*
	 * Use of two-dimensional arrays
	 * ①.understand
	 * For the understanding of two-dimensional array, it can be regarded as one-dimensional array arr1 and another one-dimensional array arr2
	 * In fact, from the perspective of the underlying operation mechanism of the array, there is no concept of multi-dimensional array
	 * 
	 * ②.
	 * a.Declaration and initialization of two-dimensional array
	 * b.Gets the element at the specified position of the array
	 * c.Gets the length of the array
	 * d.Traversal array
	 * e.Default initial value of array element
	 * f.Memory parsing of arrays
	 */
	public static void main(String[] args) {
		//a. Declaration and initialization of two-dimensional array
		//initiate static
		int[][] arr = new int[][]{{1,2,3},{2,3,4},{5,6},{7,8}};
//		int[][] arr = {{1,2,3},{2,3,4},{5,6}};  This kind of writing is also OK
		//Dynamic initialization 1
		int[][] arr1 = new int[3][2];
		//Dynamic initialization 2
		int[][] arr2 = new int[3][];
		
		
		//This is roughly the same as the discussion of "e. default initial value of array elements", and it can be skipped or ignored.
		System.out.println(arr[2][1]); //Print 6 of array arr
		System.out.println(arr1[0][0]); //Print arr[0] in array arr1 and 0 index elements in one-dimensional array
		System.out.println(arr2[0]); //Each one-dimensional array is the default initialization value null (the array is a reference type, which is null by default)
		arr2[0] = new int[3];
		arr2[1] = new int[1];
		arr2[2] = new int[2];
		System.out.println(arr2[0][0]); //At this time, the element that defaults to one-dimensional array has been initialized, and the int type defaults to 0
		System.out.println(arr2[0]); //arr2[0] is now an address value[ I@15db9742 [represents one-dimensional array, and I represents int type
		
		
		//b. How to call an element at a specified location
		String[][] names = new String[3][2];
		System.out.println(arr[2][0]); //Print 5
		System.out.println(names[2][1]); //null
		
		//c. Gets the length of the array
		System.out.println(names.length); //3
		System.out.println(names[0].length); //2
		System.out.println(arr.length); //3
		
		System.out.println("**********************");
		
		//d. Traversal array
		for(int i = 0;i < arr.length;i++){
			for(int j = 0;j < arr[i].length;j++){
				System.out.print(arr[i][j] + " ");
			}
			System.out.println();
		}
		
		System.out.println("**********************");
		//e. Default initial value of array elements (key understanding)
		/*
		 * Use of 2D arrays:
		 * Regulation: the two-dimensional array is divided into the elements of the outer array and the elements of the inner array
		 * int[][] arr = new int[4][3];
		 * 	Outer elements: arr[0], arr[1], arr[2], arr[3]
		 * 	Inner elements: arr[0][0], arr[0][1], arr[0][2], etc
		 * 
		 * Default initialization value for array elements
		 * For initialization method 1: for example: int[][] arr = new int[4][3];
		 * 	The initialization value of the outer element is: address value
		 * 	The initialization value of the inner element is: the same as that of the one-dimensional array
		 * For initialization methods, for example: int[][] arr = new int[4] [];
		 * 	The initialization value of the outer element is null
		 * 	The initialization value of the inner element is: it cannot be called, otherwise an error will be reported.
		 */
		int[][] arrInt = new int[4][3];
		System.out.println(arrInt[0]); //[ I@6d06d69c Address value
		System.out.println(arrInt[0][0]); //0
		
		float[][] arrFloat = new float[4][3];
		System.out.println(arrFloat[0]); //[ F@7852e922 Address value
		System.out.println(arrFloat[0][0]); //0.0
		
		short[][] arrShort = new short[4][3];
		System.out.println(arrShort[0]); //[ S@4e25154f Address value
		System.out.println(arrShort[0][0]); //0
		
		System.out.println("**********************");
		char[][] arrChar = new char[4][3];
		System.out.println(arrChar[0]); // Address value 
		System.out.println(arrChar[0][0]); //
		
		String[][] arrString = new String[4][3];
		System.out.println(arrString[0]); //[Ljava.lang.String;@70dea4e address value
		System.out.println(arrString[0][0]); //null

		System.out.println("**********************");
		double[][] arrDouble = new double[4][3];
		System.out.println(arrDouble[0]); // [ D@5c647e05 Address value 
		System.out.println(arrDouble[0][0]); //0.0
		
		arrDouble = new double[4][];
		System.out.println(arrDouble[0][0]);//Error null pointer exception NullPointerException
	}
}
4.1 memory analysis of two-dimensional array
①,Analyze the memory structure diagram of the following code:

int[][] arr1 = new int[4][];
arr1[1] = new int[]{1,2,3};
arr1[2] = new int[4];
arr1[2][1] = 30;

②,Analyze the memory structure diagram of the following code:

int[][] arr4= new int[3][];
System.out.println(arr4[0]);//null
System.out.println(arr4[0][0]);//report errors
arr4[0] = new int[3];
arr4[0][1] = 5;
arr4[1] = new int[]{1,2};

③,Analyze the memory structure diagram of the following code:

int[][] arr = new int[3][];
arr[1] = new int[]{1,2,3};
arr[2] = new int[3];
System.out.println(arr[0]);//null
System.out.println(arr[0][0]);//Report exception

④,Analyze the memory structure diagram of the following code:

int[][] arr1= newint[4][];
arr1[0] = new int[3];
arr1[1] = new int[]{1,2,3};
arr1[0][2] = 5;
arr1 = new int[2][];

4.2 practice of two-dimensional array

Exercise 1:

Code demonstration:

package com.rucoding.d7;

/**
 * @author LiuYiXin
 *
 */
public class ArraySumDemo03 {
	public static void main(String[] args) {
		//Sum as shown
		int sum = 0;
		int[][] arr = new int[][]{{3,5,8},{12,9},{7,0,6,4}};
		for(int i = 0;i < arr.length;i++){
			for(int j = 0;j < arr[i].length;j++){
				sum += arr[i][j];
			}
		}
		System.out.println("The sum is:" + sum);
	}
}

Exercise 2:

int[] x this is a one-dimensional array, int[] y [] this is a two-dimensional array, that is, int[][] y

tips: the same type or bottom-up transformation.

Exercise 3:

/* Print a 10 Line Yang Hui triangle using a two-dimensional array.
 *
 * [[prompt]
 * 1. The first line has 1 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 elements.
 * Namely: yanghui[i][j] = yanghui[i-1][j-1] + yanghui[i-1][j];
 */

First output the overall frame and create a two-dimensional array new int[10] [] with a length of 10. By default, the initialization value of each position is 0. At this time, perform another assignment. First determine that the beginning and end of each line are 1.

Fill in 1 at the beginning and end of each line, and assign values to other positions according to the prompted formula.

Example code:

package com.rucoding.d7.exer;

/**
 * @author LiuYiXin
 *
 */
public class YangHuiArrayDemo01 {
//	Print a 10 Line Yang Hui triangle using a two-dimensional array.
	public static void main(String[] args) {
		//Determines the length of the array
		int[][] arr = new int[10][];
		for(int i = 0;i < arr.length;i++){
			//Initialize one-dimensional array length
			arr[i] = new int[i + 1];
			//Assignment of leading and trailing elements
			arr[i][0] = 1;
			arr[i][i] = 1;
			
			//Assign values to non leading and trailing elements
			for(int j = 1;j < i;j++){//Cycle condition J < arr [i]. Length-1; 
				arr[i][j] = arr[i-1][j] + arr[i-1][j-1];
			}
			
		}
		
		//Traversal output array
		for(int i = 0;i < arr.length;i++){
			for(int j = 0;j < arr[i].length;j++){
				System.out.print(arr[i][j] + "\t");
			}
			System.out.println();
		}
		
	}
}

Exercise 4 (interview questions):

Create a length of 6 int Type array, the required value is 1-30,At the same time, the element values are different.

Code demonstration:

package com.rucoding.d7.exer;

/**
 * @author LiuYiXin
 *
 */
public class ArrayRandomDemo04 {
	public static void main(String[] args) {
		/*Create an int array with a length of 6. The values of array elements are required to be between 1-30 and assigned randomly.
		* At the same time, the values of the required elements are different.
		*
		*/
		//Defines an array of length 6
		int[] arr = new int[6];
		for(int i = 0;i < arr.length;i++){
			arr[i] = (int) ((Math.random()*30) + 1);
			System.out.println(arr[i]);
			//Judge whether the number generated randomly each time is repeated in the array
			for(int j = 0;j < i;j++){
				if(arr[i] == arr[j]){
//					i = i - 1; / / it is repeated at this time. Do not continue to the next one. Continue to perform the assignment of current i
					i--; //Put it another way
//					continue lable;
					break;
				}	
			}		
		}
		
		//ergodic
		for(int i = 0;i < arr.length;i++){
			System.out.print(arr[i] + "\t");
		}
		System.out.println();
		
			
	}
}
5. Common algorithms involved in arrays
(1),Assignment of array elements(Yang Hui triangle, loop number, etc)
(2),Find the maximum, minimum, average, sum, etc. of elements in a numeric array
(3),Copy, reverse and find of array(Linear search, dichotomy search)
(4),Sorting algorithm of array elements
5.1 assignment of array elements

View exercise 3 above < < printing of Yang Hui triangle >

5.2 basic operations of array elements

Code demonstration:

package com.rucoding.d7.exer;

/**
 * @author LiuYiXin
 *
 */
public class ArrayBasicOperationDemo01 {
	/*
	 * Investigation of the algorithm: find the maximum, minimum, average, sum, etc. of the elements in the numerical array
	 * 
	 * Define a one-dimensional array of int type, containing 10 elements, and assign some random integers respectively,
	 * Then find the maximum, minimum, sum and average values of all elements and output them.
	 * Requirement: all random numbers are two digits.
	 * 
	 * [10,99]
	 * Formula: (int)(Math.random() * (99 - 10 + 1) + 10)
	 */

	public static void main(String[] args) {
		
		//Defines an array of length 10
		int[] arr = new int[10];
		//Define variables
		int maxNum = 0;
		int minNum = 0;
		int sum = 0;
		double aveNum = 0.0;
		
		int len = arr.length;
		
		
		//Array
		for(int i = 0;i < arr.length;i++){
			//Outputs a random number between 10 and 99
			arr[i] = (int) (Math.random()*(99 - 10 + 1) + 10);
		}
		
		
		//Find the maximum value
		for(int i = 0;i < arr.length;i++){
			if(maxNum < arr[i]){
				maxNum = arr[i];
			}
		}
		
		//Find the minimum value
		minNum = arr[0];
		for(int i = 0;i < arr.length;i++){
			if(minNum > arr[i]){
				minNum = arr[i];
			}
		}
		
		//Sum
		for(int i = 0;i < arr.length;i++){
			sum += arr[i];
		}
		
		//Average
		aveNum = sum / len;
		
		//Traversal array
		for(int i = 0;i < arr.length;i++){
			if(i != arr.length -1){
				System.out.print(arr[i] + ",");
			}else{
				System.out.print(arr[i]);
			}
			
		}
		
		System.out.println();
		System.out.println("Maximum" + maxNum);
		System.out.println("minimum value" + minNum);
		System.out.println("the sum" + sum);
		System.out.println("average value" + aveNum);
		
	}	
}
5.3 basic operations of array elements 2

Code demonstration:

package com.rucoding.d7.exer;

/**
 * @author LiuYiXin
 *
 */
public class ArrayBasicOperationDemo02 {
	/*
	 * Use simple arrays
	 * (1)Create a class named ArrayTest, and declare array1 and array2 variables in the main() method. They are arrays of type int [].
	 * (2)Using curly braces {}, initialize array1 to 8 prime numbers: 2,3,5,7,11,13,17,19.
	 * (3)Displays the contents of array1.
	 * (4)Assign the array2 variable equal to array1, modify the even index element in array2 to make it equal to the index value (for example, array[0]=0,array[2]=2). Print out array1.
	 */

	public static void main(String[] args) {
		int[] array1,array2;
		array1 = new int[]{2,3,5,7,11,13,17,19};
		
		//Display the contents of array1
		for(int i = 0;i < array1.length;i++){
			System.out.print(array1[i] + "\t");
		}
		
		//Assign the array2 variable equal to array1
		array2 = array1;  //Here is the assignment of array, not copy!
		
		//Modify the even index element in array2 to make it equal to the index value (for example, array[0]=0,array[2]=2)
		for(int i = 0;i < array2.length;i++){
			if(i % 2 == 0){
				array2[i] = i;
			}
		}
		
		System.out.println();
		
		//Print out array1.
		for(int i = 0;i < array1.length;i++){
			System.out.print(array1[i] + "\t");
		}
		
	}
	
}

To solve this problem, stop and think:

Thinking 1: above array1 and array2 What's the relationship?
//array1 and array2 have the same address values and both point to a unique array entity in heap space.
int[] array1,array2;
array1 = new int[]{2,3,5,7,11,13,17,19};
array2 = array1; //The assignment actually points to the same address value in the heap space
for(int i = 0;i < array2.length;i++){
	if(i % 2 == 0){
		array2[i] = i;
	}
}

Memory structure analysis diagram:

Thinking 2: How array2 yes array1 Copy of array
int[] array1,array2;
array1 = new int[]{2,3,5,7,11,13,17,19};
//Copy of array
array2 = new int[array1.length]; //New keyword is to create an object and open up a new space
for(int i = 0;i < array2.length;i++){
	array2[i] = array1[i];
}

Memory structure analysis diagram:

5.4. Copy, reverse and search of array

Code demonstration:

package com.rucoding.d7.exer;

/**
 * @author LiuYiXin
 *
 */
public class ArrayBasicOperationDemo04 {
	/*
	 * Investigation of algorithm: array copy, inversion and search (linear search and dichotomy search)
	 */
	public static void main(String[] args) {
		//Copy of array
		String[] arr = new String[]{"CC","FF","SS","QQ","YY","XX","TT","KK","EE","GG"};
		String[] arr1 = new String[arr.length];
		for(int i = 0;i< arr1.length;i++){
			arr1[i] = arr[i];
		}
		
		//ergodic
		for(int i = 0;i< arr1.length;i++){
			System.out.print(arr1[i] + "\t");
		}
		
		System.out.println();
		
		//The inversion of the array takes into account the head and tail swapping
//		int index = 0;
//		int endIndex = arr1.length -1;
//		while(index < endIndex){
//			//Exchange two numbers, as previously written, and define a temporary variable
//			String temp = arr1[index];
//			arr1[index] = arr1[endIndex];
//			arr1[endIndex] = temp;
//			index++;
//			endIndex--;
//		}
		//Optimized writing
		for(int i = 0,j = arr1.length - 1;i < j;i++,j--){
			String temp = arr1[i];
			arr1[i] = arr[j];
			arr[j] = temp;
		}
		
		//Traversal output
		for(int i = 0;i< arr1.length;i++){
			System.out.print(arr1[i] + "\t");
		}
		
		System.out.println();
		
		//Find (that is, search) 
		//Linear search
		boolean isFlag = true;
		String target = "HH";
		for(int i = 0 ;i < arr1.length;i++){
			if(target.equals(arr1[i])){ //The string uses the equals() method
				isFlag = false;
				System.out.println("eureka");
				break;
			}
		}
		if(isFlag){
			System.out.println("Unfortunately, no corresponding one was found");
		}	
		
 	}
}

Bisection search of search (half search)

Illustration:

Code demonstration:

package com.rucoding.d7.exer;

/**
 * @author LiuYiXin
 *
 */
public class ArrayBasicOperationDemo04 {
	/*
	 * Investigation of algorithm: array copy, inversion and search (linear search and dichotomy search)
	 */
	public static void main(String[] args) {
		//Binary search (half search): the premise is that the array to be searched is orderly
		int[] arr2 = new int[]{-8,-314,22,24,53,66,79,105,98,123};
		int targetNum = 12;
		int headIndex = 0; //Initial first index
		int endIndex = arr2.length - 1;  //Initial last index
		boolean isFlag2 = true;
		while(headIndex <= endIndex){
			int middleIndex = (headIndex + endIndex) / 2;		
			if(targetNum == arr2[middleIndex]){
				System.out.println("eureka");
				isFlag2 = false;
				break;
			}else if(targetNum > arr2[middleIndex]){
				headIndex = middleIndex + 1; 
			}else{
				endIndex = middleIndex - 1;
			}		
		}
		
		if(isFlag2){
			System.out.println("Unfortunately, no corresponding one was found");
		}
		
 	}
}
5.5 sorting algorithm of array elements
(1),Sort: assume to contain n The sequence of records is{R1,R2,...,Rn},The corresponding keyword sequence is{K1,K2,...,Kn}. Reorder these records to{Ri1,Ri2,...,Rin},Make the corresponding keyword value meet the requirements Ki1<=Ki2<=...<=Kin,Such an operation is called sorting.
Generally speaking, the purpose of sorting is to find quickly.
(2),Measure the advantages and disadvantages of sorting algorithm:
	Time complexity: analyze the comparison times of keywords and the movement times of records
	Spatial complexity: analyze how much auxiliary memory is needed in the sorting algorithm
	Stability: if two records A and B The keyword values of are equal, but after sorting A,B If the order of is kept unchanged, the sorting algorithm is said to be stable.
(3),Sorting algorithm classification: internal sorting and external sorting.
	Internal sorting: the whole sorting process does not need the help of external memory (such as disk), and all sorting operations are completed in memory.
	External sorting: there are a lot of data involved in sorting, and the amount of data is very large. The computer cannot complete the whole sorting process in memory, so it must use external memory (such as disk).
	The most common external sort is multiway merge sort. It can be considered that external sorting is composed of multiple internal sorting.

5.5.1. Top ten internal sorting algorithms

(1),Select sort
	Direct selection sorting and heap sorting
(2),Exchange sort
	Bubble sorting(Key grasp),Quick sort(Just know for a while)
(3),Insert sort
	Direct insert sort, half insert sort Shell sort
(4),Merge sort
(5),Bucket sort
(6),Cardinality sort

reminder: The above algorithms focus on mastering handwritten bubble sorting and quick sorting for the time being. Others who are interested and have time to study.

5.5.2 five features of the algorithm

Insert picture description here

5.5.3 bubble sorting (important)

Basic idea of bubble sorting:
By comparing the sorting codes of adjacent elements from the front to the back of the sequence to be sorted, if the reverse order is found, it will be exchanged, so that the elements with larger sorting codes will gradually move from the front to the rear.
Because in the sorting process, each element is constantly close to its own position. If there is no exchange after a comparison, it indicates that the sequence is orderly. Therefore, a flag should be set in the sorting process swap Determine whether elements have been exchanged. This reduces unnecessary comparisons.

Graphic demonstration

Code demonstration (handwritten):

package com.rucoding.d7.exer;

/**
 * @author LiuYiXin
 *
 */
public class BubbleArrayDemo {
	public static void main(String[] args) {
		//Classic sort: bubble sort
		int[] arr = new int[]{12,-34,4,18,40,-2,0,78}; //len 8
		//
		for(int i = 0;i < arr.length - 1;i++){ //Note the conditional part of the loop
			for(int j = 0;j < arr.length - 1 - i;j++){  //Note the conditional part of the loop
				//Two numbers are exchanged with each other
				if(arr[j] > arr[j+1]){
					int temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}
			}
		}
		
		for(int i = 0;i < arr.length;i++){
			System.out.print(arr[i] + "\t");
		}
		
	}
}

5.5.4. Quick sorting (beginner Java, for understanding only)

Sorting idea:

Picking out an element from a sequence is called"benchmark"(pivot),
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).
After the partition, the benchmark is in the middle of the sequence. This is called a partition( partition)Operation.
Recursively( recursive)Sort the subsequence of the element less than the reference value and the subsequence of the element greater than the reference value.
The bottom case of recursion is that the size of the sequence is zero or one, that is, it has always been sorted. Although recursion continues, the algorithm will always end, because in each iteration( iteration)In, it will put at least one element in its final position.

Graphic demonstration:

5.5.5 performance comparison of sorting algorithms

Performance comparison of various internal sorting methods:

(1),In terms of average time: quick sort is the best. But in the worst case, the time performance is not as good as heap sort and merge sort.
(2),From the perspective of algorithm simplicity: because the algorithms of direct selection sorting, direct insertion sorting and bubble sorting are relatively simple, they are considered as simple algorithms Shell Sort, heap sort
	 Quick sort and merge sort algorithms, which are complex, are considered as complex sort.
(3),In terms of stability, direct insertion sort, bubble sort and merge sort are stable, while direct selection sort, quick sort Shell Sort and heap sort are unstable sorts
(4),Number of records to be sorted from n In terms of size, n If it is small, simple sorting should be adopted; and n Improved sorting should be adopted in case of large.

Selection of sorting algorithm:
(1), if n less(as n≤50),Direct insertion or direct selection sorting can be adopted. When the record scale is small, direct insertion sorting is better; otherwise, the number of records directly selected for movement is less than that directly selected	  When inserting, it is better to select and sort directly.
(2), If the initial status of the file is basically in order(Correct order),Direct insertion, bubbling or random quick sorting should be selected;
(3), if n Larger, the time complexity shall be O(nlgn)Sorting method: quick sort, heap sort or merge sort.
6. Use of Arrays tool class
java.util.Arrays Class is a tool class for manipulating arrays, which contains various methods for manipulating arrays, such as sorting and searching.
boolean equals(int[] a,int[] b)Determine whether two arrays are equal
String toString(int[] a)Output array information
void fill(int[] a,int val)Fills the array with the specified value
void sort(int[] a)Sort arrays
int binarySearch(int[] a,int key)Binary the sorted array to retrieve the specified value

Code demonstration:

package com.rucoding.d7.exer;

import java.util.Arrays;

/**
 * @author LiuYiXin
 *
 */
public class ArraysUtilDemo {
	public static void main(String[] args) {
		//1.boolean equals(int[] a,int[] b) judge whether two arrays are equal
		int[] arr1 = new int[]{1,2,3,4};
		int[] arr2 = new int[]{1,2,4,3};
		boolean isEquals = Arrays.equals(arr1, arr2);
		System.out.println(isEquals);
		
		//2.String toString(int[] a) output array element information
		System.out.println(Arrays.toString(arr1)); //[1, 2, 3, 4]
		System.out.println(Arrays.toString(arr2)); //[1, 2, 4, 3]
		
		
		//3.void fill(int[] a,int val) fills the specified value into the array
		Arrays.fill(arr1, 2);
		System.out.println(Arrays.toString(arr1)); //[2, 2, 2, 2]
		
		//4.void sort(int[] a) sort the array
		Arrays.sort(arr2);
		System.out.println(Arrays.toString(arr2)); //[1, 2, 3, 4]
		
		//5.int binarySearch(int[] a,int key) dichotomy the sorted array to retrieve the specified value.
		int[] arr = new int[]{12,-34,4,18,40,-2,0,78};
		Arrays.sort(arr);
		System.out.println(Arrays.toString(arr)); //Default ascending order
		int index = Arrays.binarySearch(arr, 24);
		if(index >= 0){ //If the underlying key cannot be found, it returns a negative number
			System.out.println(index);
		}else{
			System.out.println("unfortunately, Can't find! " + index);
		}
		
	}
}
7. Common exceptions in array usage
Common exceptions in arrays:
(1),Exception of array subscript out of bounds:ArrayIndexOutOfBoundsException
(2),Null pointer exception:NullPointerException

Code demonstration:

package com.rucoding.d7.exer;

/**
 * @author LiuYiXin
 *
 */
public class ArrayExceptionDemo {
	/*
	 * Common exceptions in arrays:
	 * 1.Exception for array subscript out of bounds: ArrayIndexOutOfBoundsException
	 * 
	 * 2.Null pointer exception: NullPointerException
	 * 
	 */
	public static void main(String[] args) {
		//1. Exception of array subscript out of bounds: ArrayIndexOutOfBoundsException
		int[] arr = new int[]{1,2,3,4};
		//Error scenario 1
		for(int i = 0;i <= arr.length;i++){
//			System.out.println(arr[i]); //java.lang.ArrayIndexOutOfBoundsException
		}
		
		//Error scenario 2
//		System.out.println(arr[-2]);

		//2. Null pointer exception: NullPointerException
		int[] arr1 = new int[]{1,2,3,4};
		arr1 = null;
		//Error scenario 1
//		System.out.println(arr1[0]); //java.lang.NullPointerException
		//Error scenario 2
		int[][] arr2 = new int[4][];
//		System.out.println(arr2[0][0]);
		//Error scenario 3
		String[] arr3 = new String[]{"AA","QQ","YY","XX","TT","KK"};
		arr3[0] = null;
		System.out.println(arr3[0].toString());
		
	}
}

This article ends here. Thank you for browsing~

Posted by celestineweb on Wed, 13 Oct 2021 08:31:07 -0700