Java array (multidimensional, Arrys, sorted, sparse)

Keywords: Java Algorithm

  • Array overview
  • Array declaration creation
  • Array usage
  • Multidimensional array
  • Arrays class
  • Sparse array

Definition of array

  • An array is an ordered collection of data of the same type
  • Array describes several data of the same type, which are arranged and combined in a certain order
  • Each data is called an array unit, and each array element can access them through a subscript

Array declaration creation

  • First, you must declare an array variable. Syntax:

  • dataType[] arrayRefVar; //Preferred method
    int [] nums; 
    dataType arrayRefVar[]; //The effect is the same, but not preferred, C language
    int nums[]; 
    int[] nums1 = new int[10];  //close
    
  • Java uses new to create arrays. Syntax:

  • dataType[] arrayRefVar = new dataType[arraySize];
    nums = new int[10]; //There can be 10 numbers of int type
    
  • The elements of the array are accessed through the index. The array index starts from 0

  • Get array length: arrays.length

  • An error is reported: java.lang.arrayindexoutofboundsexception (array subscript out of bounds). The fetched number exceeds the set length

Memory analysis

  • heap

    • new objects and arrays
    • It can be shared by all threads without storing other object references
  • Stack

    • Store the basic variable type (including the specific value of this and exhaust type)
    • The variable of the reference object (the specific address of the reference in the heap will be stored)
  • Method area

    • Can be shared by all threads
    • Contains all class and static variables

Three kinds of initialization

  • initiate static

  • int[] a = {1,2,3,4};
    //quote
    Man[] mans = {new Man(),new Man()};
    
  • dynamic initialization

  • int[] a = new int [2];
    a[0] = 1;
    a[1] = 2;
    
  • Array default initialization

    • Array is a reference type, and its elements are equivalent to the instance variables of the class. Therefore, once the array is allocated space, each single element is implicitly initialized in the way of the nursery rhyme of instance variables
    • The array element has no assignment. The default value is 0

Four basic characteristics of arrays

  • Its length is determined. Once an array is created, its size cannot be changed (unless it is recreated)
  • Its elements must be of the same type, and mixed types are not allowed
  • The elements in the array can be any data type, including basic and reference types
  • Array variables belong to the reference type, and arrays can also be regarded as objects. Each element in the array is equivalent to the member variables of the object. The array itself is an object. In Java, the object is in the heap (new). Therefore, whether the array saves the original type or other object types, the array object itself is in the heap

Array boundary

  • Legal range of subscript: [0, length-1]. If it exceeds the range, an error will be reported

  • public static void main (String[] args) {
        int[] a = new int[2];
        System.out.println(a[2]);
    }
    
  • java.lang.ArrayIndexOutOfBoundsException: 2: array subscript out of bounds exception

  • Summary:

    • An array is an ordered collection of the same data type (the data type can be any type)
    • Arrays are also objects. Array elements are equivalent to member variables of objects
    • The array length is fixed and immutable. If it is out of bounds, it will report: ArrayIndexOutofBounds

Use of arrays

  • For loop (common)
  • For each loop (no subscript)
  • Array as method input parameter
  • Array as return value

example:

	public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6};
        //JDK1,5 has no subscript
        for (int i : arr) {
            System.out.println(i);
        }
//        printArray(arr);
        printArray(reverse(arr));
    }

    //Print array elements
    public static  void printArray(int[] arr){
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]+" ");
        }
    }

    //Invert array
    public static int[] reverse(int[] arrays){
        int[] a = new int[arrays.length];
        for (int i = 0; i < arrays.length; i++) {
            a[arrays.length-1-i] = arrays[i];
        }
        return a;
    }

Multidimensional array

  • Multidimensional array can be regarded as an array of arrays. Two dimensional array is a special one-dimensional array, and each element is a one-dimensional array (the elements in the array are arrays)
  • Two dimensional array: int [] [] array = {1,2}, {1,2};

example

	public static void main(String[] args) {
        /*
            array[0]  1,2   array[0][0] = 1 array[0][1] = 2
            array[1]  2,3   array[1][0] = 2 array[1][1] = 3
         */
        int[][] array = {{1,2},{2,3}};
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                System.out.print(array[i][j]+" ");
            }
            System.out.println();
        }
    }

Arrays class

  • Array tool class java.util.Arrays
  • There are no methods for us to call the array object itself, but the API provides a tool class Arrays for us to use, so we can perform some basic operations on the data object
  • View JDK documentation
  • All the methods in the Arrays class are static methods with static modifiers. When using them, you can call them directly with the class name and "don't use" objects (Note: it's "don't use", not "can't")
  • It has the following common functions:
    • Assign a value to the array: through the fill method
    • Sort the array: sort in ascending order through the sort method
    • Compare arrays: use the equals method to compare whether the element values in the array are equal
    • Find array elements: binary search can be performed on the sorted array through the binarySearch method
        int[] a = {1,2,33,44,21123,53123,41,22};
        System.out.println(a);//[I@1b6d3586
        //Print array elements
//        System.out.println(Arrays.toString(a));
//        printArra(a);
        Arrays.sort(a);//Array sorting, ascending by default
        System.out.println(Arrays.toString(a));//[1, 2, 22, 33, 41, 44, 21123, 53123]
        Arrays.fill(a,3,5,0);
        System.out.println(Arrays.toString(a));//[1, 2, 22, 0, 0, 44, 21123, 53123]

Bubble sorting

  • Two adjacent numbers are compared. The first number is small, and the position is changed to the left / right
		int[] arr = {1,3,2,5,4,7};
		int a = 0;
        //Outer cycle, judge how many cycles
        for (int i = 0; i < arr.length-1; i++) {
            //Inner loop, compare and judge two numbers. If the first number is larger than the second, exchange the position
            for (int j = 0; j < arr.length-i-1; j++) {
                /*
                    Subtract 1 each time in the cycle, and it is not necessary to compare the last digit: arr.length-i-1 5 4 3 2 1
                    Then compare the adjacent two numbers in turn
                 */
                if (arr[j+1]>arr[j]) {
                    a = arr[j+1] ;
                    arr[j+1] = arr[j];
                    arr[j] = a;
                }

            }
        }
  • The bubbling code is relatively simple. The two-layer cycle, the number of bubbling wheels in the outer layer and the inner layer are compared in turn
  • When we see nested loops, we should immediately get that the time complexity of this algorithm is O(n^2)
  • Thinking: how to optimize?
    public static void main(String[] args) {
        int[] a = {1,3,2,5,4,7};
        System.out.println(Arrays.toString(sort(a)));
    }
    /*/
        Bubble sorting
        1,Compare arrays, adjacent numbers, the first is larger than the second, and exchange positions
        2,No more than one round, get a maximum number or a minimum number
        3,The next round can be one less cycle
        4´╝îCycle successively until the end
     */
    public static int[] sort(int[] arr){
        int a = 0;
        //Outer cycle, judge how many cycles
        for (int i = 0; i < arr.length-1; i++) {
            //Reduce meaningless comparisons through flag representation
            boolean flag = false;
            //Inner loop, compare and judge two numbers. If the first number is larger than the second, exchange the position
            for (int j = 0; j < arr.length-i-1; j++) {
                /*
                    Subtract 1 each time in the cycle, and it is not necessary to compare the last digit: arr.length-i-1 5 4 3 2 1
                    Then compare the adjacent two numbers in turn
                 */
                if (arr[j+1]>arr[j]) {
                    a = arr[j+1] ;
                    arr[j+1] = arr[j];
                    arr[j] = a;
                    flag = true;
                }
            }
            //If there is no exchange position, it means that the sorting has been completed, and the cycle can be terminated
            if (flag == false) {
                break;
            }
        }
        return arr;
    }

Sparse array

  • Requirements: in the preparation of Gobang game, it has the functions of saving, exiting and continued hanging.

  • Analysis problem: because many values of two-dimensional array are 0 by default, many meaningless data are recorded

  • Solution: sparse array

    • When most elements in an array are 0 or an array with the same value, you can use a sparse array to save the array
    • Sparse arrays are processed in the following ways:;
      • How many rows and columns are there in the record array? How many different values are there
      • The elements, rows, columns and values with different values are recorded in a small-scale array, so as to compress the size of the applet
    • As shown in the figure: the original array is on the left and the sparse array is on the right

demonstration

  • Convert original array to sparse array
    • Calculate the number and value of valid data and store them in the new array
  • Convert sparse array to original array
    • Restore according to rows, columns and values of sparse array
    public static void main(String[] args) {
        //1 create a two-dimensional array, 9 * 9 0: lattice. 1: Black flag: 2: white chess
        int[][] arr = new int[9][9];
        arr[1][2] = 1;
        arr[2][3] = 2;
        arr[4][4] = 1;
        arr[5][1] = 2;
        arr[6][7] = 1;
        //Output raw array
        System.out.println("Original array:");
        for (int[] ints : arr){ //Shortcut: arr.for
            for (int anInt : ints){
                System.out.print(anInt+" ");
            }
            System.out.println();
        }
        /*
        Print results:
				Original array:
				0 0 0 0 0 0 0 0 0
				0 0 1 0 0 0 0 0 0
				0 0 0 2 0 0 0 0 0
				0 0 0 0 0 0 0 0 0
				0 0 0 0 1 0 0 0 0
				0 2 0 0 0 0 0 0 0
				0 0 0 0 0 0 0 1 0
				0 0 0 0 0 0 0 0 0
				0 0 0 0 0 0 0 0 0
         */
        //Convert to sparse array to save
        //1. Get the number of valid values
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length; j++) {
                if (arr[i][j] != 0) {
                    count++;
                }
            }
        }
        System.out.println("Valid values are:"+count+"individual");

        //2 create a sparse array
        int[][] arr2 = new int[count+1][3];
        arr2[0][0] = arr.length;
        arr2[0][1] = arr.length;
        arr2[0][2] = count;
        //Traverse the two-dimensional array and store non-zero values in the sparse array
        int count2 = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                if (arr[i][j]!=0){
                    count2++;
                    arr2[count2][0] = i;
                    arr2[count2][1] = j;
                    arr2[count2][2] = arr[i][j];
                }
            }
        }
        //Output sparse array
        System.out.println("Sparse array:");
        for (int i = 0; i < arr2.length; i++) {
            System.out.println(arr2[i][0]+" "+arr2[i][1]+" "+arr2[i][2]+" ");
        }
        /*
						Sparse array:
						9 9 5 
						1 2 1 
						2 3 2 
						4 4 1 
						5 1 2 
						6 7 1
         */
        //Restore sparse array
        //1 read sparse array
        int[][] arr3 = new int[arr2[0][0]][arr2[0][1]];
//        arr3[arr2[1][0]][arr2[1][1]] = arr2[1][2];
//        arr3[arr2[2][0]][arr2[2][1]] = arr2[2][2];
        //2 restore value
        for (int i = 1; i <= arr2[0][2]; i++) {
            arr3[arr2[i][0]][arr2[i][1]] = arr2[i][2];
        }
        System.out.println("Restore array:");
        for (int[] ints : arr3){ //Shortcut: arr.for
            for (int anInt : ints){
                System.out.print(anInt+" ");
            }
            System.out.println();
        }
        /*
				Restore array:
				0 0 0 0 0 0 0 0 0 
				0 0 1 0 0 0 0 0 0 
				0 0 0 2 0 0 0 0 0 
				0 0 0 0 0 0 0 0 0 
				0 0 0 0 1 0 0 0 0 
				0 2 0 0 0 0 0 0 0 
				0 0 0 0 0 0 0 1 0 
				0 0 0 0 0 0 0 0 0 
				0 0 0 0 0 0 0 0 0        
         */
    }

Posted by kb0000 on Wed, 10 Nov 2021 12:39:37 -0800