java quick start -- array, two-dimensional array

Posted by Gibbs on Mon, 29 Nov 2021 05:41:38 +0100

array

Introduction: it can store multiple data of the same type. Array is also a data type, a reference type, that is, array is a group of data

package com.company.hello;

import java.util.Scanner;

/**
 * Getting started with arrays
 *
 * @author L.yn
 * @version 1.0
 * @date 2021/11/21 9:21
 */
public class ArrayTest {
    public static void main(String[] args) {
        //Define an array
        /**
         * 1,double[] Represents an array of type double, with the array name hens
         * 2,{3, 5, 1, 3.4, 2, 50}Represents the value / element of an array
         */
        double[] hens = {3, 5, 1, 3.4, 2, 50};

        //Traverse the array to get the sum of all elements of the array
        /**
         * You can access the elements of the array through hens [subscript], which starts from 0. For example, the first element is hens[0]
         * Through circular access
         */
        for (double hen : hens) {
            System.out.println(hen);
        }
        for (int i = 0; i < hens.length; i++) {
            System.out.println(hens[i]);
        }

        //Demo loop input five grades, save to double array, and output
        //1. Create a double array with a size of 5
        double[] score = new double[5];
        //2. Cyclic input
        for (int i = 0; i < score.length; i++) {
            System.out.println("Please enter a value for the element");
            double aDouble = new Scanner(System.in).nextDouble();
            score[i] = aDouble;
        }
        //Output, traversal array
        for (double v : score) {
            System.out.println(v);
        }
    }
}

Use of arrays

  1. Usage 1 - dynamic initialization
    1. Definition of array
      Data type [] array name = new data type [size]
      int[] arr = new int[5];// An array named arr is created to hold five ints
      Description: This is a method to define an array

    2. Array reference (use)

      1. Array name [subscript / index], for example: you want to use the third number A[2] of array A
  2. Usage 2 - dynamic initialization
    1. Declare array first
      Syntax: data type [] array name
      int[] arr;
    2. Create array
      Syntax: array name = new data type [size]
      arr = new int[10]
  3. Usage 3 - static initialization
    1. Initialize array
      Syntax: data type [] array name = {element value, element value...}
      int[] arr = {1,2,3,4,5,...}

Array usage considerations and details

  1. Array is a combination of multiple data of the same type to realize the unified management of these data
  2. The elements in the array can be any data type, including basic type and reference type, but they cannot be mixed
  3. After the array is created, if there is no assignment, there is a default value
  4. To work with arrays
    1. Declare an array and open up space
    2. Assign values to each element of the array
    3. Use array
  5. The subscript of the array starts at 0
  6. Array subscript must be used within the specified range, otherwise: subscript out of range exception is reported
  7. Array is a reference type, and array data is an object

Array assignment mechanism

  1. Basic data type assignment. This value is specific data and does not affect each other
    int n1 = 2; int n2 = n1;
  2. By default, arrays are passed by reference, and the assigned value is the address

sort

Introduction to sorting

Sorting is the process of arranging a group of data in a specified order

Sorted classification

  • Internal sorting:
    It refers to loading all data to be processed into internal memory for sorting. Including (exchange sort, selection sort and insertion sort)

  • External sort method:
    The amount of data is too large to be loaded into memory, so it needs to be sorted with the help of external storage. Including (merge sort and direct merge sort)

  • Bubble sorting
    Through the sequence to be sorted from the back to the front (starting from the elements with larger subscripts), compare the values of adjacent elements in turn. If it is found that the reverse order is exchanged, so that the elements with larger values gradually move from the front to the back, and gradually rise like bubbles under the water

    package com.company.hello;
    
    /**
     * Bubble sorting
     *
     * @author L.yn
     * @version 1.0
     * @date 2021/11/28 16:02
     */
    public class BubbleSort {
        public static void main(String[] args) {
            /**
             * The five disordered: 24, 69, 80, 57, 13 are arranged into an ordered sequence from small to large by bubble sorting
             * thinking
             * The first round of sorting: the goal is to put the maximum number last
             * First comparison: [24,69,80,57,13]
             * Second comparison: [24,69,80,57,13]
             * Third comparison: [24,69,57,80,13]
             * Fourth comparison: [24,69,57,13,80]
             *
             * The second round of sorting: the target puts the second largest number in the penultimate position
             * First comparison: [24,69,57,13,80]
             * Second comparison: [24,57,69,13,80]
             * Third comparison: [24,57,13,69,80]
             *
             * The third round of sorting: the goal puts the third largest number in the penultimate position
             * First comparison: [24,57,13,69,80]
             * Second comparison: [24,13,57,69,80]
             *
             * The fourth round of sorting: the goal puts the fourth largest number in the penultimate position
             * First comparison: [13,24,57,69,80]
             *
             * Summarize the bubble sorting characteristics
             * 1:  There are five elements
             * 2:  There are four rounds of sorting, which can be regarded as an outer cycle
             * 3:  Each round of sorting can determine the position of a number. For example, the first round of sorting can determine the maximum number
             * 4:  When comparing, if the preceding number is less than the following number, it is exchanged
             * 5:  Each round of comparison is decreasing by 4 - > 3 - > 2 - > 1
             */
            int[] arr = {24, 69, 80, 57, 13};
            int temp = 0;//Variables for auxiliary exchange
            for (int i = 0; i < arr.length - 1; i++) {
                for (int j = 0; j < arr.length - 1 - i; j++) {
                    //If the preceding number > the following number, swap
                    if (arr[j] > arr[j + 1]) {
                        temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                    }
                }
                /**
                 * Round 1
                 * 24	69	57	13	80	
                 * Round 2
                 * 24	57	13	69	80	
                 * Round 3
                 * 24	13	57	69	80	
                 * Round 4
                 * 13	24	57	69	80	
                 */
                System.out.println("\n The first" + (i + 1) + "round");
                for (int ae : arr) {
                    System.out.print(ae + "\t");
                }
            }
    
        }
    }
    
    

lookup

introduce

In java, we often use two kinds of search

  • Sequential search

    package com.company.hello;
    
    import java.util.Scanner;
    
    /**
     * Sequential search
     *
     * @author L.yn
     * @version 1.0
     * @date 2021/11/28 16:41
     */
    public class SeqSearch {
        public static void main(String[] args) {
            /**
             * There is a number series: white eyebrow eagle king, Golden Lion King, purple shirt Dragon King, Green Wing bat King guessing game:
             * Enter a name arbitrarily from the keyboard to judge whether the name is included in the sequence [sequential search]
             * Requirement: if found, prompt to find and give the subscript
             *
             * thinking
             * 1, Define an array of strings
             * 2, Receive user input, traverse the array and compare them one by one. If there is any, prompt the information and exit
             */
    
            //Define an array of strings
            String[] name = {"White browed eagle king", "Golden King ", "Purple Dragon King", "Green winged bat King"};
            System.out.println("Please enter a name");
            String findName = new Scanner(System.in).nextLine();
            boolean deflag = true;
            for (int i = 0; i < name.length; i++) {
                //Compare the string equals. If you want to find the name, it is the current element
                if (findName.equals(name[i])) {
                    System.out.println("Congratulations on finding:" + findName);
                    System.out.println("subscript=" + i);
                    deflag = false;
                    break;
                }
            }
            if (deflag){
                //Can't find
                System.out.println("Can't find...");
            }
        }
    }
    
  • binary search

Multidimensional array – 2D array

package com.company.hello;

/**
 * Getting started with 2D arrays
 *
 * @author L.yn
 * @version 1.0
 * @date 2021/11/28 16:54
 */
public class TwoDimensionalArray {
    public static void main(String[] args) {
        /**
         * Quick start cases:
         * Please output the following graphics with a two-dimensional array
         * 0 0 0 0 0 0
         * 0 0 1 0 0 0
         * 0 2 0 3 0 0
         * 0 0 0 0 0 0
         *
         * What is a two-dimensional array
         * 1:  By definition, int [] []
         * 2:  It can be understood that each element of the original one-dimensional array is a one-dimensional array, which constitutes a two-dimensional array
         */
        int[][] arr = {
                {0, 0, 0, 0, 0, 0},
                {0, 0, 1, 0, 0, 0},
                {0, 2, 0, 3, 0, 0},
                {0, 0, 0, 0, 0, 0}
        };
        //Key concepts of binary array
        //1. Gets the number of elements of a binary array
        System.out.println("Number of elements of binary array:" + arr.length);
        //2. Each element of a two-dimensional array is a one-dimensional array, so if you need to get the value of each one-dimensional array, you need to traverse again
        //3. If we want to access the j-th value arr[i][j] of the I + 1st one-dimensional array


        //Export 2D graphics
        for (int i = 0; i < arr.length; i++) {
            //Traverse each element of a two-dimensional array (array)
            /**
             * arr[i]Represents the i+1 element of a two-dimensional array, such as arr[0]: the first element of a two-dimensional array
             * arr[i].length Get the length of each corresponding one-dimensional array
             *
             * 0	0	0	0	0	0
             * 0	0	1	0	0	0
             * 0	2	0	3	0	0
             * 0	0	0	0	0	0
             */
            for (int j = 0; j < arr[i].length; j++) {
                System.out.print(arr[i][j] + "\t");//Output one-dimensional array
            }
            System.out.println();//Line feed
        }
    }
}

Use of two-dimensional arrays

  • Mode of use I

    • Syntax: Types[][] Array name = new type[size][size]
      For example: int[][] arr = new int[3][5]
          package com.company.hello;
      
      /**
       * @author L.yn
       * @version 1.0
       * @date 2021/11/28 17:15
       */
      public class TwoDimensionalArray01 {
          public static void main(String[] args) {
      
              int[][] arr = new int[2][3];
              for (int i = 0; i < arr.length; i++) {
                  for (int j = 0; j < arr[i].length; j++) {
                      /**
                       * 0  0  0
                       * 0  0  0 
                       */
                      System.out.print(arr[i][j] + "  ");
                  }
                  System.out.println();
              }
          }
      }
      
  • Mode of use II

    • Declare type first[][] Array name;
      In the definition (open space) array name = new type[size][size]
      Assignment (with default values, e.g int Type is 0)
      
  • Mode of use III

    • Look at a requirement: dynamically create the following binary array and output it

      package com.company.hello;
      
      /**
       * @author L.yn
       * @version 1.0
       * @date 2021/11/28 17:34
       */
      public class TwoDimensionalArray02 {
          public static void main(String[] args) {
              //Dynamically create a binary array and output it
              int[][] arr = new int[3][];
              for (int i = 0; i < arr.length; i++) {
                  //Make room for each one-dimensional array
                  //If the one-dimensional array new is not given, then arr[i] is null
                  arr[i] = new int[i + 1];
      
                  //Traverse the one-dimensional array and assign a value to the one-dimensional array
                  for (int j = 0; j < arr[i].length; j++) {
                      arr[i][j] = i + 1;
                  }
      
                  /**
                   * 1
                   * 2	2
                   * 3	3	3
                   */
                  for (int j = 0; j < arr[i].length; j++) {
                      System.out.print(arr[i][j] + "\t");
                  }
                  System.out.println();
              }
          }
      }
      
  • Usage 4: static initialization

    • Definitions: Types[][] Array name = {{Value 1, value 2,...},{Value 1,....},...}
      For example:
          int[][] arr = {{1,2,3,4},{1,2,3},{1}};
      Interpretation:
          1, Defines a two-dimensional array arr
          II arr There are three elements (each element is a one-dimensional array)
          3, The first one-dimensional array has four elements, the second one-dimensional array has three elements, and the third one-dimensional array has one element
      
  • Traversal of binary array

    • package com.company.hello;
      
      /**
       * Traversal of two-dimensional array
       *
       * @author L.yn
       * @version 1.0
       * @date 2021/11/28 18:12
       */
      public class TwoDimensionalArray03 {
          public static void main(String[] args) {
              int[][] arr = {{1, 2}, {3, 2, 1}, {-2}};
              /**
               * Traverse the two-dimensional array and get and
               *
               * thinking
               * 1, Traverse the two-dimensional array and accumulate the values to int sum
               */
              int sum = 0;
              /**
               * Output the value of the binary array
               * 1	2	
               * 3	2	1	
               * -2	
               * And: 7
               */
              System.out.println("Outputs the value of a binary array....");
              for (int i = 0; i < arr.length; i++) {
                  for (int j = 0; j < arr[i].length; j++) {
                      sum += arr[i][j];
                  }
      
                  for (int j = 0; j < arr[i].length; j++) {
                      System.out.print(arr[i][j] + "\t");
                  }
                  System.out.println();
              }
              System.out.println("And:" + sum);
          }
      }
      
      
  • Use details and precautions of binary array

    • One dimensional arrays are declared in the following ways: int[] x or int x []

    • Two dimensional arrays are declared in the following ways:

      int[][] x perhaps int[] x[] perhaps int x[][]
      
    • A two-dimensional array is actually composed of multiple one-dimensional arrays. The length of each one-dimensional array can be the same or different. For example, map [] [] is a two-dimensional array
      Map [] [] = {1,2}, {3,4,5} is composed of map[0] which is a one-dimensional array containing two elements, map[1] which is a one-dimensional array containing three elements. We also become a two-dimensional array with different columns

Topics: Java Back-end