Java Learning - Part 1 - Phase 1 - Section 5: Arrays, Sorting, and Finding

Array, Sort, and Find


Array Introduction

Arrays can hold multiple data of the same type. Arrays are also a data type, a reference type. That is, an array is a set of data

Array Quick Start

//1. double[] means an array of type double, the array name hens
//2. {3, 5, 1, 3.4, 2, 50} represents the values/elements of an array, which in turn represents the values of an array
//Element number
double[] hens = {3,5,1,3.4,2,50};
//Traverse the array to get the sum of all the elements of the array, using for
//1. We can access the elements of the array by hens [subscript]
//Subscripts are numbered from the day, for example, the first element is hens[o]
//The second element is hens[1], and so on
//2. for allows you to loop through the elements/values of an array
//Teacher's Tip: You can get the size/length of the array by its name.length
System.out.println("The length of the array=" + hens.length);
for( int i = 0; i < 6; i++){
    System.out.println("No."+(i+1)+"Value of elements=" + hens[i]);

Use of arrays

Mode of Use 1 - Dynamic Initialization
Definition of arrays

Data type array name = new data type [size]
int a[]=new int[5];// Creates an array with the name a and five ints

Mode of Use 2 - Dynamic Initialization

_Declare the array first
Syntax: Array name of data type; It can also be a data type [array name;
int a[]; Or int[] a;

_Create an array
Syntax: Array name = new data type [size;
a=new int[10];

_Case Demo [Modify earlier]

//(2) The second dynamic allocation, declaring the array first, then new allocating space
double scores[] ;//Declare the array, when scores is null
scores = new double[5];// Allocate memory space to store data

Mode of Use 3 - Static Initialization

Initialize Array
Syntax: data type array name []={element value, element value...)
int a[]={2,5,6,7,8,89,90,34,5,6}, if you know how many elements there are in the array, the use above the specific value is equivalent to:

int a[=new int[9];
a[0]=2;a[1]=5;a[2]=6; a[3]=7;a[4]=8;

_Quick Start Case [Chicken Farm]

double hensl={];equivalence
double hens[ = new double[6];
hens[0] = 3; hens[1] = 5; hens[2] = 1; hens[3] = 3.4; hens[4]=2;hens[5] = 50;

Array usage considerations and details

  1. Arrays are a combination of multiple data of the same type to achieve uniform management of these data
  2. Elements in an array can be of any data type, including basic and reference types, but cannot be mixed.
  3. After the array is created, if there is no assignment, there are default values of int 0, short 0, byte 0, long 0, float 0.0,double 0.0, char \u0000,boolean false,String null
  4. Step 1 using arrays. Declare the array and open up space 2. Assign 3 to each element of the array. Using arrays
  5. The subscript of an array starts at 0.
  6. Array subscripts must be used within a specified range, otherwise: the subscript crosses an exception, such as int[] arr=new int[5]; Then the valid subscript is 0-4
  7. Arrays are of reference type, and array data is an object

Array assignment mechanism

  1. Basic data type assignment, which is specific data and does not affect each other.
    int n1 = 2; int n2 =n1;
  2. Arrays are passed by reference by default and assigned an address. Take a look at an example and analyze the memory map (emphasis) of the array assignment.
    int[] arr1 = {1,2,3};
    int[] arr2 = arr1;
//Basic data type assignment, value copy
//The change of n2 does not affect the value of n1
int n1 = 10;
int n2 = n1;
n2 = 80;
System.out.print1n( "n1=" +n1);//10
System.out.print1n( "n2=" + n2);//80
//Arrays are passed by reference by default, assigned by address, and assigned by reference
//Is an address, changes in arr2 affect arr1
int[]arr1 = {1,2,3};
int[]arr2 = arr1;//Assign arr1 to arr2
arr2[0] = 10;

//Look at the value of arr1
System.out.println( "====arr1 Elements of====");for(int i = 0; i < arr1.length; i++){

JVM Memory Situation Diagram

Array Copy

Write code to implement array copy (content copy)
Put int[l] arr1 = {10,20,30}; Copying to an arr2 array requires that the data space be independent.

int[] arr1 = {10,20,30};

//Create a new array arr2 to open up a new data space
//Size arr1.length;
int[] arr2 = new int[arr1.length];

//Calculate arr1, copy each element to the corresponding position of arr2
for(int i = 0; i < arr1.length; i++){
    arr2[i] = arr1[i];

Array Expansion

Scanner myScanner = new Scanner(;//Initialize Array
int[]arr = {1,2,3};
    int[]arrNew = new int[arr.length + 1];
    //Traverse the arrarray, copying the elements of arr to the arrNew array in turn
    for(int i =0; i< arr.length; i++){
        arrNew[i] = arr[i];
    System.out.println("Please enter the element you want to add");
    int addNum = myScanner.nextInt();
    //Assign addNum to the last element of arrNew
    arrNew[ arrNew.length - 1] = addNum;
    //Let arr point to arrNew,
    arr = arrNew;
    //Output arr to see the effect
    System.out.println("====arr Element condition after expansion====");
    for(int i = 0; i < arr.length; i++){
        System.out.print(arr[i] + "\t");
    //Ask User Is//Ask User Continue
    System.out.println("Do you want to continue adding y/n");
    char key = ).charAt(0);
    if( key =='n'){//If n is entered, it ends
System.out.println("You quit adding...");


Sorting is the process of sorting a group of data in a specified order. Sorted classification:

  1. Internal Sorting:
    All data that needs to be processed is loaded into internal memory for sorting. Includes (Exchange Sort, Selective Sort and Insert Sort);
  2. External Sorting:
    The amount of data is too large to be fully loaded into memory and external storage is needed to sort. Includes (merge sort and direct merge sort).

bubble sort

The basic idea of Bubble Sorting is that by comparing the values of adjacent elements from the back to the front (starting with the larger subscript) of the sequence to be sorted, the values of adjacent elements are exchanged if an inverse order is found, so that the elements with larger values move forward and backward gradually, rising up like bubbles under water.

Bubble Sorting Act Example:

Below we will give a specific case to illustrate the bubble method. We put five disorders: 24,69,80,57,13 into an ordered sequence from smallest to largest using bubble sorting.

Summarize the characteristics of bubble sorting
1. We have five elements in total
2. There are 4 rounds of sorting, which can be seen as an outer loop
3. Each round of sorting can determine the position of a number, such as the first round sorting to determine the maximum number, the second round sorting to determine the second largest number position, and so on
4. When making comparisons, if the number before is greater than the number after, exchange
5. Each round of comparison is decreasing 4->3->2->4 analysis ideas->code..


In java, there are two common lookups:
1. Sequential Search
2.Dichotomy Search [Dichotomy, we put it in the algorithm explanation]

* Case demo:
1. There is a number of columns: Eagle King, Golden Lion King, Dragon King Purple Shirt, Bat King Guess Count Game: Enter a name from the keyboard to determine if the column contains this name [Search in sequence] Requirements: If found, prompt to find and give subscript values.

//Define a string array
String[] names = {"Eagle King","Golden King","Dragon King Purple","King Green-Winged Bat"};
Scanner myScanner = new Scanner(;
System.out.println("Please enter a name");
String findName =;
//Calendar array, compare one by one, if there is a prompt, and exit//Here the teacher gives you a programming idea
int index = -1;
for(int i = 0; i < names.length; i++){
    //Compare strings Compare equals if the name to be found is the current element
        System.out.println("Congratulations on finding"+ findName);
        System.out.println("Subscript is " + i); 
        //Save i to index
        index = i;
        break;//Sign out
if(index == -1){//Can't find
    System.out.println("sorry ,Can't find" + findName);

2. Binary an ordered array to find {1,8,10,89,1000,1234}. Enter an array to see if the number exists, and find the subscript. If not, prompt "No number".

Answer: omitted

Multidimensional Array

Multidimensional arrays We will only talk about two-dimensional arrays.

2-D Array

Application scenarios for two-dimensional arrays
For example, if we develop a game of Gobang, the board needs a two-dimensional array to represent it.

//1. int[][] as defined
//2. It can be understood that each element of the original one-dimensional array is a one-dimensional array, which forms a two-dimensional array.
int[][ ]arr = { {0,0, 0,0,0,0},
//Output 2-D Graphics
for(int i = 0; i < arr.length; i++){
    //Each Yuan Qin of a two-dimensional array
    //Approximate each element of a two-dimensional array (array)
    //Lao-Korean Interpretation
    //1. arr[i] denotes the first i+1 yuan of a two-dimensional array, such as arr[0]:the first yuan of a two-dimensional array
    //2. arr[i].length gets the length of each one-dimensional array
    for(int j = 0; j <arr[i].length; j++){
        System.out.print(arr[i][j] + "\t");//Output one-dimensional array
    System.out.println();//Line Break

Usage 1: Dynamic Initialization

  1. Syntax: type [][] array name = new type [size] [size]

  2. For example: int[][] a[][]=new int[2][3]

  3. Use Demo

  4. Existence of two-dimensional arrays in memory

Usage Mode 2: Dynamic Initialization

  1. First declare: type array name [][];

  2. Redefine (open space) array name = new type [size] [size]

  3. Assignment (defaults, such as int of type 0)

  4. Use Demo

    int arr[][];//Declare a two-dimensional array
    arr = new int[2][3];//Reopen Space

Usage 3: Dynamic Initialization - Uncertain Number of Columns

  1. Look at one requirement: Dynamically create the following two-dimensional array and output it.

  1. Complete the case

  2. Draw execution analysis diagram

    int[][] arr = new int[3][];//Create a two-dimensional array, but only determine the number of one-dimensional arrays
    for(int i = 0; i < arr.length; i++){//Exercise arr for each one-dimensional array
        //Open space new for each one-dimensional array
        //If a one-dimensional array is not given new, arr[i] is null
        arr[i] = new int[i + 1];
        //Traverse through one-dimensional arrays and assign values to each element of the one-dimensional array
        for(int j = 0;j < arr[i].length; j++){
            arr[i][j] = i + 1;//assignment
    System.out.println( "=====arr element=====");//Linear output
    for(int i = 0; i < arr.length; i++){
        //Each one-dimensional array of output arr
        for(int j = 0; j < arr[i].length; j++){
            System.out.print(arr[i][i]+" ");
        System.out.println();//Line Break

Usage Mode 4: Static Initialization

  1. Define type array name []={{Value 1, Value 2.}, {Value 1, Value 2.}, {Value 1, Value 2.}}

  2. Use it [fixed access]
    For example:
    int[][] arr = {{1,1,1), {8,8,9}, {100});


  1. Defines a two-dimensional array arr
  2. arr has three elements (each element is a one-dimensional array)
  3. The first one-dimensional array has three elements, the second one-dimensional array has three elements, and the third one-dimensional array has one element

Details and considerations for using two-dimensional arrays

  1. One-dimensional arrays are declared as:
    Int[] or int x[]
  2. Two-dimensional arrays are declared as:
    int[][]y or int[]y[] or int y[][]
  3. Two-dimensional arrays are actually composed of multiple one-dimensional arrays, each of which can have the same or different length. For example, a map [[] is a two-dimensional array
    int map[][] = {{1,2},{3,4,5}}
    map[0] is a one-dimensional array with two elements, and map[1] is a one-dimensional array with three elements, also known as a two-dimensional array with unequal number of columns.

Tags: Java

Posted by noobh on Sat, 02 Jul 2022 01:46:27 +0930