[Java Learning note]java definition of an array of basic language basics & Common operations (traversal, sort, find) & two-dimensional arrays

Source: Internet
Author: User

1. Array Basics

1. What is an array:

A collection of data of the same type is a container.

2. Benefits of Arrays:

The zero-based numbering of elements in an array can be automated to facilitate manipulation of the data.

3. Format: (once created, must be clear length)

Format 1:

element type [] Array name = new element type [the number of elements is the length of the array];

Example: int[] array = new INT[5];

Format 2:

element type [] Array name = new element type []{element 1, element 2 ...} ;

Example: int[] array = new int[]{1,2,3,4,5};

Int[] array = {1,2,3,4,5};

The array has a default value: (It can be used without initialization because the array new int[5] is an instance of heap memory, and the instance in heap memory has a default initial value)

such as int[] array = new INT[5];

System.out.pritln (Array[0]);

The result is 0.

Common errors:

1. Array subscript out of bounds exception

int New int [3]; System.out.println (arr[3]);

Description: Compile will not error, run times wrong. ArrayIndexOutOfBoundsException

This exception is reported when a subscript that does not exist in the array is accessed.

2. Null pointer exception

int New int [3null; System.ou.println (arr[0]);

Description: Same compilation will not error, run times wrong. Nullpointeexception

Null pointer exception, which is reported if the variable is accessed when there is no entity pointing to the reference type variable.

2. Common Operations for arrays

1. Traverse

Print all the elements in an array

int [] arr = {43,6,645,43,3,2,1,54};  for (int i=0; i<arr.length; i++) {    System.out.print ("arr[" +i+ "]:" +arr[i]+ ";"); }

2. Get the maximum value

Get maximum Value

 Public int getmax (int[] arr) {    int max = arr[0];//record element value     for (  int i = 1; i<arr.length; i++) {        if(arr[i]>max) {            = arr[i];        }    }     return Max;}

 Public Static int getmax (int[] arr) {    int maxindex = 0;   Record element subscript for     (int i = 1; i<arr.length; i++) {        if (arr[i]>Arr[maxindex]) {            = arr[i];        }    }     return Arr[maxindex];}

3. Sorting

The Java API provides a way to sort: java.util.Arrays.sort (arr);

1. Select the Sorting method

Principle:

Code:

 public void selectsort (int[] arr) {        int  temp;          for (int i = 0; i<arr.length-1; i++) {            for (int j = i+1; j<arr.length; j++<
    
      c13>) {                
     if(arr[i]>
     arr[j]) {//                    swap =
      arr[i]                    ; =
      Arr[j];                     =
      temp;}}        }
    
}

2. Bubble Sorting method

Principle:

Code:

 public  static  void  bubblesort (int  [] arr)    { int   temp;  for  (int  i = 0; i<arr.length-1; i+ + for  ( int  j = 0; j<arr.length-1-i; J++ if  (Arr[j]>arr[j+1 = Arr[j];                ARR[J]  = Arr[j+1];           Arr[j  +1] = temp; }       }    }        }

* Package Interchange Code:

// swap position of two elements in an array  Public Static void swap (intintint  b) {    int temp = Arr[a];     = Arr[b];     = Arr[a];}

Select sorting performance Optimizations:

As shown, because the array is stored in the heap memory, repeating the extra swap position will result in redundant operations, so the thought of defining the intermediate variable to record the minimum value each time, and then the corresponding position of the exchange, this can reduce the number of exchanges, improve efficiency.

Code:

 Public Static voidSelectsort_2 (int[] arr) {                 for(inti = 0; i<arr.length-1; i++) {            intnum =Arr[i]; intindex =i;  for(intj = i; j<arr.length; J + +) {//Inner Loop is responsible for finding the smallest element in the remaining elements                if(num>Arr[j]) {num= Arr[j];//record the smallest element with Numindex = j;//use Index to record the subscript of the smallest element                }            }
            if (index!=i) {                swap (arr, I, index); // swap the most recent element to be sorted and find the smallest element position
            }        }    }

4. Find

1. Find where an element first appears

Code:

 Public Static int getindex (intint  num) {        for (int i = 0; i<arr.length; i + +)            {if(num==arr[i])                {return  i;            }        }         return -1;    }

2. Two-point lookup (binary lookup)

* * Suitable for ordered arrays

The Java API also provides a two-point lookup. Java.util.Arrays.binarySearch (Int[],target), if present, returns the subscript, if not present, returns-insertion point-1

Code:

1. Recursive method:

 Public Static intFindintArry[],intTargetintBeginindex,intEndIndex) {    if(Beginindex >EndIndex) {        return-1; }    intMiddleindex = (beginindex + endIndex)/2; if(Arry[middleindex] = =target) {        returnMiddleindex; } Else if(Arry[middleindex] <target) {Beginindex= Middleindex + 1; } ElseEndIndex= MiddleIndex-1; returnfind (Arry, Target, Beginindex, EndIndex);}

2.while Cycle

1.

 Public Static intHalfsearch (int[] arr,inttarget) {    intmin = 0, max = arr.length-1, mid = (min + max)/2;  while(Arr[mid]!=target) {//        if(target>Arr[mid]) min= Mid + 1; Else if(target<Arr[mid]) Max= Mid-1; if(max<min) {            return-1; } Mid= (min + max)/2; }    returnmid;}

2.

 Public Static intHalfsearch (int[] arr,inttarget) {    intmin = 0, max = arr.length-1, mid;  while(max>=min) {Mid= (min + max)/2; if(target>Arr[mid]) min= Mid + 1; Else if(target<Arr[mid]) Max= Mid-1; Else            returnmid; }    return-1;}

Interview question: Given an ordered array, if an element is stored in an array, and the array is guaranteed to be ordered, then the stored corner of the element is obtained.

Answer: Directly using the above binary lookup function, return 1 to return to Min.

3. Two-dimensional array

Format 1:int[][] arr = new int[3][2];

    • Defines a two-dimensional array called arr
    • 3 one-dimensional arrays in a two-dimensional array
    • Each of the one-dimensional arrays has 2 elements
    • The names of one-dimensional arrays are arr[0],arr[1],arr[2]
    • To the first one-dimensional array 1 subscript is assigned a value of 78 is: arr[0][1]=78;

Format 2:int[][] arr = new int[3][];

    • 3 one-dimensional arrays in a two-dimensional array
    • Each one-dimensional array is the default initialization value of NULL
    • These 3 one-dimensional arrays can be initialized individually

Arr[0] = new INT[3];

ARR[1] = new INT[1];

ARR[2] = new INT[2];

Format 3:int[][] arr = {{1,2},{3,4,5,6},{7,8,9}};

Consider the following code:

int[] arr =New int[3] [2]; System.out.println (arr);//[[ Email protected]System.out.println (Arr[0]);//[[Email protected]System.out.println (Arr[0][0]);//0int[] arr2 =New int[3][]; System.out.println (ARR2);//[[ Email protected]System.out.println (Arr2[0]);//NULLSystem.out.println (Arr2[0][0]);//NullPointerException

Description

The first way to define this is to save an ARR variable in the stack memory to record the address value of the two-dimensional array in heap memory. A two-dimensional array is created in heap memory, which opens up three contiguous spaces to hold the first address values of three one-dimensional arrays. There are also three entities in the heap memory that correspond to one-dimensional arrays, and each element of a one-dimensional array has a default initialization value of 0.

The second way to define this is to save an ARR variable in the stack memory to record the address value of the two-dimensional array in heap memory. A two-dimensional array is created in heap memory, opening up three contiguous spaces the default initialization value is NULL.

Acquisition of the length of a two-dimensional array:

The length of the two-dimensional array is obtained by arr.length, and the number of one-dimensional arrays in the two-dimensional array is obtained. Such as:

int [] arr = new int[3][2];

The value of Arr.length is 3.

Arr[0].length gets the length of the first one-dimensional array.

By the world is my bed

--------------------------------------------------------------------------------------------------------------- -----------------finished-------

[Java Learning note]java The definition of an array of basic language basics & Common operations (traversal, sort, find) & two-dimensional arrays

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.