Java basic grammar learning day06---beginners must read detailed explanation

1. Array

1.1 What is an array

  • Program = algorithm + data structure;
  • The if, if-else, switch, and loop learned earlier all solve process problems, that is, algorithm problems.
  • The so-called data structure simply means storing data according to a specific structure, and designing a reasonable data structure is a prerequisite for solving problems.
  • An array is the most basic data structure.
- 相同数据类型的元素组成的集合
- 元素按线性顺序排列。所谓线性顺序是指除第一个元素外,每一个元素都有唯一的前驱元素;除最后一个元素外,每一个元素都有唯一的后继元素(“一个跟一个”)
- 可以通过元素所在位置的顺序号(下标)做标识来访问每一个元素(下标从0开始,最大到元素个数-1

1.2 Definition of array

Syntax for declaring an array:

       数据类型[  ]   数组名 = new  数据类型 [ 大小 ] ;
例:  int [  ]     arr    = new       int      [   10  ] ;

illustrate:

  • Array type, int[] indicates that each element in the array is of type int.
  • Array type variable (reference).
  • The length of the array, that is, the number of elements in the array.

1.3 Array initialization

After the basic type of array is created, the initial value of its elements: byte, short, char, int, long is 0; float and double is 0.0; boolean is false. The elements of the array can be initialized at the same time as the array declaration, for example
:

  int [ ] arr = {
    
     10,23,30,-10,21 } ; 

This writing method can only be used for initialization at the time of declaration, not for assignment. For example, the following code will have a compilation error.

 int [ ] arr;
    arr = {
    
     10,23,30,-10,21 } ; 

The declared array type variable can be initialized in the following ways:

   int [ ] arr ;  
   arr = new int[ ]{
    
    10,23,30,-10,96 } ;

Note: The length cannot be written in [], the number of elements is the length of the array.

1.4 Array access

Get the length of the array

You can get the length of the array by calling the length property of the array:

   int[] arr = new int[]{
    
     3,6,8,9 };
   int len = arr . length ;
   System.out.println(“数组长度为:+ len);
  上述代码输出结果为:数组长度为:4

Access array elements by subscript

The elements in the array are accessed by subscript:

例如:
            int[ ] arr = new int[]{
    
     4,5,6,8};
            int  temp = arr [ 2 ];   // 获取第3个元素—6
            // 交换数组下标为2和3的两个相邻元素的值
            int  temp = arr [ 2 ] ;
            arr [ 2 ] = arr [ 3 ] ;
            arr [ 3 ] = temp ; 
            // 交换后结果:4,5,8,6

iterate over array elements

Traverse the array elements, usually choose the for loop statement, the loop variable is used as the subscript to access the array elements, and you can access each element in the array

  int[] arr = new int[10];  
     for ( int i = 0 ; i < arr.length ; i ++ ){
    
    
            arr [ i ] = 100;
      }

Note: The loop counter varies from 0 to length- 1

Traverse the array elements, output in positive order

int [ ] arr = new int [ ] {
    
    10,20,30,40,50 } ;
   for ( int i=0; i< arr.length; i++) {
    
    
    System.out.println ( arr[ i ] ) ;
   }

Traverse the array elements, output in reverse order

int [ ] arr = new int [ ] {
    
    10,20,30,40,50 } ;
   for ( int i = (arr.length -1) ; i >= 0 ; i -- ) {
    
    
  System.out.println ( arr[ i ] ) ;
   }

Exercise: Find the maximum value of an array element

1.5 Copying of arrays

The System.arraycopy method is used for array copying

Arrays can be copied using the System.arraycopy( ) method

public static void arraycopy(Object src, int srcPos,
                            Object dest, int destPos, int length)
src		– 源数组
srcPos		– 源数组中的起始位置
dest		– 目标数组
destPos	– 目标数组中的起始位置
length 	– 要复制的数组元素的数量

The System.arraycopy method is used for array copying

int[ ] a   = {
    
     10 ,20 ,30 ,40 ,50 };
int[ ] a1 = new int[ 6 ] ;
System.arraycopy( a , 1 , a1 , 0 , 4 );    

insert image description here

Arrays.copyOf method for array copying

Arrays can be copied using the copyOf method of the java.util.Arrays class

  类型[ ]  newArray  = Arrays.copyOf ( 
                    类型[ ]  original , int  newLength );

Features: The generated new array is a copy of the original array
. If the newLength is smaller than the source array, it will be intercepted.
If the newLength is greater than the source array, it will be filled with 0 or null.
Therefore, the generated new array can be greater than the length of the source array.

int [ ]  a = {
    
     10,20,30,40,50 } ;
 int [ ]   a1 = Arrays . copyOf (  a, 6 ); 
  a1数组元素为: 10 20 30 40 50 0

Array expansion

The length of the array cannot be changed after it is created. The so-called expansion refers to creating a new larger array and copying the contents of the original array into it.
Arrays can be expanded easily through the Arrays.copyOf() method.

   int [ ]  a = {
    
     10,20,30,40,50 } ;
     a = Arrays . copyOf (  a, a.length+1 );
     
     输出a数组元素:10,20,30,40,50,0

Exercise: Find the maximum value of the array elements and put them in the last place

  • Finds the maximum value among the elements of an array and places the maximum value at the position next to the last element of the array.

1.6 Array sorting

Sorting instructions for arrays

排序是对数组施加的最常用的算法;
所谓排序,是指将数组元素按照从小到大或从大到小的顺序重新排列;
对于元素较多的数组,排序算法的优劣至关重要;
一般情况下,通过排序过程中数组元素的交换次数来衡量排序算法的优劣;
常用的排序算法有:插入排序、冒泡排序、快速排序等。

Array Bubble Sort Algorithm

  • The principle of bubble sorting: compare adjacent elements, and exchange if the last order criterion is violated
  • It can be simplified and understood as:
    • Find the largest of all elements for the first time and place it in the last position without any change;
    • Find the largest of all remaining elements for the second time and put it in the penultimate position without changing;
    • And so on until sorting is complete.
  • The comparison can be achieved by either "sinking" or "floating".

insert image description here

Bubble sort algorithm implementation

  • Declare an array containing the following 12 elements, and perform bubble sorting on it
    [32, 58, 38, 48, 43, 60, 13, 34, 20, 47, 87, 20]
import java.util.Random;
import java.util.Arrays;

public class BubbleSort {
    
    
	public static void main(String[] args) {
    
    
		//创建数组
		int[] arr = new int[10];
     Random ran = new Random();
		for (int i = 0; i < arr.length; i++) {
    
    
			arr[i] = ran.nextInt(100);
		}
		System.out.println(Arrays.toString(arr));
		// 冒泡排序
		System.out.println("----------冒泡排序 开始----------");
		for (int i = 0; i < arr.length - 1; i++) {
    
    
			for (int j = 0; j < arr.length - i - 1; j++) {
    
    
				if (arr[j] > arr[j + 1]) {
    
    
					int t = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = t;
				}
			}
			System.out.println(Arrays.toString(arr));
		}
		System.out.println("----------冒泡排序 结束----------");
		System.out.println(Arrays.toString(arr));
	}
}

Arrays.sort method for array sorting

The Arrays.sort() method provided by JDK encapsulates the array sorting algorithm:

int[ ] arr = {
    
     49, 81, 1, 64, 77, 50, 0, 54, 77, 18 };
Arrays.sort ( arr ) ;
for( int i=0; i<arr.length; i++) {
    
    
	System.out.println( arr[i] );
}
输出结果:0  1  18  49  50  54  64  77  77  81

Guess you like

Origin blog.csdn.net/weixin_43639180/article/details/117525879