Java Learning: Java Arrays

3. Java array

3.1 Overview of arrays

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

  • The array itself is a reference data type , and the elements in the array can be of any data type , including primitive data types and reference data types.
  • Creating an array object will open up a whole continuous space in memory, and the array name refers to the first address of this continuous space.
  • Once the length of the array is determined, it cannot be modified .
  • We can directly call the element at the specified position by subscript (or index), which is very fast.
  • Classification of arrays:

According to the dimension: one-dimensional array, two-dimensional array, three-dimensional array, ...
According to the data type of the element: the array of basic data type elements, the array of reference data type elements (that is, object array)

3.2 Use of one-dimensional arrays

① How to declare a one-dimensional array
type var[] 或 type[] var;
For example:

int a[];
int[] a1;
double b[];
String[] c; //引用类型变量数组

When declaring an array in the Java language, its length (the number of elements in the array) cannot be specified , for example: int a[5]; //Illegal

②Initialization of one-dimensional array

  • Dynamic initialization: array declaration and allocation of space for array elements and assignment operations are performed separately

     int[] arr = new intr[3];
     arr[0] = 3;
     arr[1] = 9;
     arr[2] = 8;
     
     String names[];
     names =new =String[3];
     names[0] = "钱学森";
     names[1] = "邓稼先";
     names[2] = "袁隆平";
    
  • Static initialization: Allocate space and assign values ​​to array elements while defining the array .

    int arr[] = new int []{3,9,8};
    int [] arr = {3,9,8};
     
    String names[] = {
    "李四光”,"茅以升","华罗庚"
    }
    

③Array element reference

  • define and use operatornewAfter allocating space for it, you can refer to each element in the array;
  • The reference method of the array element: array name [array element subscript]
    the array element subscript can be an integer constant or an integer expression. Such as a[3], b[i], c[6*i]; the
    array element subscript starts from 0; the legal subscript value range of an array with a length of n: 0 —>n-1 ; such as int a[] =new int[3]; The array elements that can be referenced are a[0], a[1], a[2]
  • Each array has an attribute length to indicate its length, for example: a.length indicates the length (number of elements) of array a.
    Once the array is initialized, its length is immutable .

④ Default initialization value of array elements
Array is a reference type, and its elements are equivalent to member variables of the class . Therefore, once the space is allocated in the array, each element in it is also implicitly initialized in the same way as member variables. For example:

public class Test {
    
    
	public static void main(String args[]){
    
    
	int a[]= new int[5];
	System.out.println(a[3]); //a[3]的默认值为0
}
}
>对于基本数据类型而言,默认初始化值各有不同
>对于引用数据类型而言,默认初始化值为null(注意与0不同!)
array element type Element default initial value
byte 0
short 0
int 0
long 0L
float 0.0F
double 0.0
char 0 or written as: '\u0000' (expressed as empty)
boolean false
reference type null

⑤ Create an array of basic data types

  • Using keywords in Javanewto create the array
  • The following is to create a one-dimensional array of basic data type elements
public class Tset{
    
    
	public static void main(String args[]){
    
    
		int[] s;   //处内存状态
		s = new int[10];
		for(int i=0;i<10;i++){
    
    
		s[i] = 2*i+1;
		System.out.println(s[i]);
		}
	}
}

insert image description here

public class Test{
    
    
	public static void main(String args[]){
    
    
		int[] s;
		s = new int[10];   //处内存状态
		//int[] s=new int[10];
		//基本数据类型数组在显式赋值之前,Java会自动给他们赋默认值。
		for ( int i=0; i<10; i++ ) {
    
    
			s[i] =2*i+1;
			System.out.println(s[i]);
		}
	}
}

insert image description here

public class Test{
    
    
	public static void main(String args[]){
    
    
		int[] s;
		s = new int[10];
		for ( int i=0; i<10; i++ ) {
    
    
			s[i] =2*i+1;   //处内存状态
			System.out.println(s[i]);
		}
	}
}

insert image description here
practise

/*
从键盘输入个数不确定的整数,并判断读入的正数和负数的个数,输入为0时结束程序
*/
import java.util.Scanner;
class Test 
{
    
    
	public static void main(String[] args) {
    
    
        //1.使用scanner,读取学生个数
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入学生人数:");
        int number=scanner.nextInt();
        //2.创建数组,存储学生成绩;动态初始化
        int[] scores=new int[number];
        //3.给数组中的元素赋值
        System.out.println("请输入"+number+"个学生成绩:");
        int maxScore=0;
        for (int i = 0; i < scores.length; i++) {
    
    
            scores[i]=scanner.nextInt();
            //4.获取数组中的元素最大值:最高分
            if (maxScore<scores[i]){
    
    
                maxScore=scores[i];
            }
        }
        //5.根据每个学生成绩与最高分的差值,得到每个学生的等级,并输出等级和成绩
        char level;
        for (int i = 0; i < scores.length; i++) {
    
    
            if (maxScore-scores[i]<=10){
    
    
                level='A';
            }else if (maxScore-scores[i]<=20){
    
    
                level='B';
            }else if (maxScore-scores[i]<=30){
    
    
                level='C';
            }else {
    
    
                level='D';
            }
            System.out.println("student "+i+"score is "+scores[i]+",gread is "+level);
        }
    }
}

>运行结果
请输入学生人数:
5
请输入5个学生成绩:
55
77
67
59
81
student 0score is 55,gread is C
student 1score is 77,gread is A
student 2score is 67,gread is B
student 3score is 59,gread is C
student 4score is 81,gread is A

3.3 Use of multidimensional arrays

  • The Java language provides syntax to support multidimensional arrays.
  • If one-dimensional arrays can be regarded as linear graphics in geometry, then two-dimensional arrays are equivalent to a table, like the table in Excel on the right.
  • For the understanding of two-dimensional arrays, we can see that one-dimensional array array1 exists as an element of another one-dimensional array array2. In fact, from the perspective of the underlying operating mechanism of the array, there is actually no multi-dimensional array.
    insert image description here
    insert image description here
    practise
/*1.获取arr数组中所有元素的和。*/

package test1j.ava;

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

>运行结果 54
/*2.使用二维数组打印一个 10 行杨辉三角*/

package test1j.ava;

public class yanghui {
    
    
    public static void main(String[] args) {
    
    
        int n = 10; // 控制打印的行数

        int[][] arr = new int[n][];
        for (int i = 0; i < n; i++) {
    
    
            arr[i] = new int[i + 1];
            arr[i][0] = 1;
            arr[i][arr[i].length - 1] = 1;

            // 计算该行的数据
            for (int j = 1; j < arr[i].length - 1; j++) {
    
    
                arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
            }
        }

        // 打印杨辉三角
        for (int i = 0; i < n; i++) {
    
    
            for (int j = 0; j < arr[i].length; j++) {
    
    
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }
}

>运行结果
1 
1 1 
1 2 1 
1 3 3 1 
1 4 6 4 1 
1 5 10 10 5 1 
1 6 15 20 15 6 1 
1 7 21 35 35 21 7 1 
1 8 28 56 70 56 28 8 1 
1 9 36 84 126 126 84 36 9 1 
/*3.创建一个长度为6的int型数组,要求数组元素的值都在1-30之间,且是随机赋值。同时,要求元素的值各不相同。*/

package test1j.ava;

import java.util.Random;
public class randnumber {
    
    
    public static void main(String[] args) {
    
    
        int[] nums = new int[6]; // 创建一个长度为6的int型数组
        Random rand = new Random(); // 创建一个伪随机数生成器

        // 循环生成一个数字,直到符合要求为止(1-30之间,且和数组中已有的数字不同)
        for (int i = 0; i < nums.length; i++) {
    
    
		int num;
		do {
    
    
		    num = rand.nextInt(30) + 1;
		} while (contains(nums, num, i));

		nums[i] = num; // 将符合条件的数字赋值给数组
        }

        // 打印数组的元素
    	System.out.print("随机生成的数组为{");
        for (int s=0;s<6;s++) {
    
    
        	if(s==5){
    
    
        		System.out.print(nums[s]);
        	}else
            System.out.print(nums[s]+",");
        }System.out.print("}");
        
    }

    // 判断一个数字是否已存在于数组中
    private static boolean contains(int[] nums, int num, int length) {
    
    
        for (int i = 0; i < length; i++) {
    
    
            if (nums[i] == num) {
    
    
                return true;
            }
        }
        return false;
    }
}

>运行结果
随机生成的数组为{
    
    9,15,13,17,21,11}

3.4 Common algorithms involved in arrays

  1. Assignment of array elements (Yanghui triangle, round number, etc.)
  2. Find the maximum, minimum, average, sum, etc. of elements in a numeric array
  3. Array copy, inversion, search (linear search, binary search)
  4. Algorithm for sorting array elements

Algorithm introduction
Five characteristics of the algorithm

feature meaning
Input There are 0 or more input data, these inputs must be clearly described and defined
Output At least one or more output results, no output results are not allowed
Finiteness (Finiteness) The algorithm ends automatically after a finite number of steps without infinite loops, and each step can be completed in an acceptable time
Definiteness Each step in the algorithm has a definite meaning without ambiguity
Feasibility (effectiveness, Effectiveness) Each step of the algorithm is clear and feasible, allowing users to calculate the answer with pen and paper

practise

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

package test1j.ava;

import java.util.Random;

public class suanfa1 {
    
    
	public static void main(String[] args ){
    
    
	int[] arr = new int [10];// 创建一个长度为10的int型数组
	Random rand = new Random(); // 创建一个伪随机数生成器
	// 循环生成一个数字,直到符合要求为止(两位数,>=10&&<=99)
	for(int i = 0;i<10;i++){
    
    
		int num = rand.nextInt(90)+10;
		arr[i] = num;
	}

	// 求出所有元素的最大值,最小值,和值,平均值
	 int max = arr[0], min = arr[0], sum = 0;
     for (int num : arr) {
    
    //遍历数组快捷方式
         if (num > max) {
    
    
             max = num;
         }
         if (num < min) {
    
    
             min = num;
         }
         sum += num;
     }
     double average = (double) sum / arr.length;

     // 输出结果
     System.out.println("数组元素为:");
     for (int num : arr) {
    
    
         System.out.print(num + " ");
     }
     System.out.println();
     System.out.println("最大值为:" + max);
     System.out.println("最小值为:" + min);
     System.out.println("和值为:" + sum);
     System.out.println("平均值为:" + average);
 }
}

>运行结果
数组元素为:
83 26 95 85 49 38 37 94 72 19 
最大值为:95
最小值为:19
和值为:598
平均值为:59.8

① Binary search algorithm
insert image description here

//二分法查找:要求此数组必须是有序的。

package test1j.ava;

public class erfen {
    
    

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		int[] arr3 = new int[]{
    
    -99,-54,-2,0,2,33,43,256,999};
		boolean isFlag = true;
		int number = 256;
		//int number = 25;
		int head = 0;//首索引位置
		int end = arr3.length - 1;//尾索引位置
		while(head <= end){
    
    
			int middle = (head + end) / 2;
			if(arr3[middle] == number){
    
    
				System.out.println("找到指定的元素,索引为:" + middle);
				isFlag = false;
				break;
			}else if(arr3[middle] > number){
    
    
				end = middle - 1;
			}else{
    
    //arr3[middle] < number
				head = middle + 1;
			}
		}
		if(isFlag){
    
    
		System.out.println("未找打指定的元素");
		}

	}

}

>运行结果
找到指定的元素,索引为:7

②Sorting Algorithm
Sorting:
Assume that the sequence containing n records is {R1, R2,...,Rn}, and its corresponding key sequence is {K1, K2,...,Kn}. Reorder these records into {Ri1, Ri2,...,Rin}, so that the corresponding key values ​​satisfy the condition Ki1<=Ki2<=...<=Kin, such an operation is called sorting.

Generally speaking, the purpose of sorting is to find quickly .

Measure the pros and cons of sorting algorithms:

  • Time Complexity: Analyze the number of comparisons of keywords and the number of moves of records
  • Space complexity: analyze how much auxiliary memory is needed in the sorting algorithm
  • Stability: If the key values ​​of two records A and B are equal, but the order of A and B remains unchanged after sorting, the sorting algorithm is said to be stable.

Classification of sorting algorithms: internal sorting and external sorting.

  • Internal sorting: The entire sorting process does not require external storage (such as disks, etc.), 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 entire sorting process in memory, and must rely on external storage (such as disk). The most common external sort is the multi-way merge sort . It can be considered that the external sort is composed of multiple internal sorts.

Top Ten Sorting Algorithms

  • selection sort
    direct selection sort, heap sort
  • Swap Sort
    Bubble Sort Quick Sort
  • Insertion sort
    Direct insertion sort, half insertion sort, Shell sort
  • merge sort
  • bucket sort
  • radix sort

③Bubble sort

Introduction:
The principle of bubble sorting is very simple. It repeatedly visits the array to be sorted, compares two elements at a time, and exchanges them if their order is wrong.

Sort ideas:

  1. Compare adjacent elements. If the first is greater than the second (in ascending order), swap them both.
  2. Do the same for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. After this step is done, the last element will be the largest number.
  3. Repeat the above steps for all elements except the last one.
  4. Continue repeating the above steps for fewer and fewer elements each time until there are no pairs of numbers to compare.

④ quick sort

Introduction:
Quick sort is usually significantly faster than other algorithms of the same O(nlogn), so it is often used, and quick sort adopts the idea of ​​​​divide and conquer , so you can often see the shadow of quick sort in many written test interviews. It can be seen the importance of mastering quick sorting.

Invented by Turing Award winner Tony Hoare, Quick Sort is listed as one of the top ten algorithms of the 20th century and is by far the fastest of all internal sorting algorithms. An upgraded version of bubble sort, a kind of exchange sort. The time complexity of quick sort isO(nlog(n))

Sort ideas:

  1. Pick an element from the sequence, called the " pivot " (pivot),
  2. Reorder the sequence, all elements smaller than the reference value are placed in front of the reference value, and all elements larger than the reference value are placed behind the reference value (the same number can go to either side). After this division ends, the benchmark is in the middle of the sequence. This is called a partition operation. //Big front and small back
  3. Recursively sort subarrays with elements less than the base value and subarrays with elements greater than the base value.
  4. The bottom case of recursion is that the size of the sequence is zero or one, that is, it has always been sorted. Although it has been recursively going on, this algorithm will always end, because in each iteration (iteration), it will put at least one element to its last position.

insert image description here
⑤Sorting Algorithm Performance Comparison
insert image description here

  1. In terms of average time : quicksort is the best. But in the worst case time performance is not as good as heap sort and merge sort.
  2. From the perspective of algorithm simplicity : Since the algorithms of direct selection sorting, direct insertion sorting and bubble sorting are relatively simple, they are considered as simple algorithms. For the Shell sorting, heap sorting, quick sorting and merge sorting algorithms, their algorithms are more complex and are considered complex sorting.
  3. From the perspective of stability : direct insertion sorting, bubble sorting and merge sorting are stable; while direct selection sorting, quick sorting, shell sorting and heap sorting are unstable sorting
  4. From the size of the number n of records to be sorted : when n is small, simple sorting should be used; and when n is large, improved sorting should be used.

Sorting Algorithm Selection

  1. If n comparesSmall(such as n≤50), can useinsert directlyordirect selection sort.
    When the record size is small, direct insertion sorting is better; otherwise, because the number of records moved by direct selection is less than direct insertion, direct selection sorting should be selected.
  2. If the initial state of the file is basicallyorderly, you should chooseInsertion, bubble or random quicksortappropriate;
  3. If n comparesbig, the sorting method with time complexity of O(nlgn) should be adopted:Quick Sort, Heap Sort, or Merge Sort

3.5 Common exceptions in the use of arrays

insert image description here

3.6 Use of Arrays tool class

The java.util.Arrays class is a tool class for manipulating arrays, which contains various methods for manipulating arrays (such as sorting and searching).
insert image description here

Guess you like

Origin blog.csdn.net/weixin_52357829/article/details/129403255