5. Arrays

Source: Internet
Author: User

1 arrays

1.1 Definition of an array

An array is an ordered collection of the same type. An array is a special variable that applies once to a computer for a "piece" of contiguous space. Use length to control how many exercises you want to open, and to control the size of each space by data type.

The elements of the array: the specific values that are saved in the array.

The length of the array: the number of elements in the array that can accommodate the maximum.

Data subscript: The array is represented by the subscript, the index of the array starts from 0, the maximum subscript is the length-1

Note: The element type in the array must match the data type when the array is declared.

Array element index must be integer (constant, variable, expression)

Access to arrays:

Assignment: array name [subscript]= value;

Value: array name [subscript];

Characteristics:

1. The length of the array cannot be changed once the declaration is specified

2. The data types in the array cannot be mixed (the data type of the elements in the array cannot be mixed).

Eg:public static void Test1 () {

data type [] array name =new data type [length];

int[] Nums = new INT[5];

Assignment to an array name [subscript]= value;

nums[0]=10;

Traverse

for (int i=0;i<5;i++) {

System.out.println ("nums[" +i+ "]=" +nums[i]);

}

1.2 Declaration of an array

data type [] array name; or data type array name [];

Eg:int nums[]; Int[] Nums;

The array does not allocate space when declaring, with the data name. length to get the array lengths.

Initialize default values after declaring an array:

Array of type int default value is 0

Array of type double default value is 0.0

Array of type Boolean default value False

1.3 Initialization of the array

1) declaring an array

data type [] array name;

2) initialization (array allocation space)

Array name =new data type [length];

Eg:int[] Nums;

Nums=new Int[5];

2 Assigning values

2.1 Dynamic Initialization

The declaration of an array, initialization, and assignment are written separately.

Int[] Nums;

Nums=new Int[4];

Int[] Nums=new int[4];

nums[0]=10;

...

2.2 Static initialization

The declaration of the array, initialization and assignment are completed in one step.

data type [] Array name ={value 1, value 2 ....};

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

Note: You cannot specify a length, depending on the number of elements. Must be written in a single line of statements.

Int[] Nums;

nums={1,2,3,4,5};//the wrong wording.

Int[]nums=new int[]{1,2,3,4,5};//Correct

3 Advanced for Loop (For-each) loop

Advanced for Loop (For-each Loop): New features after JDK1.5.

Grammar:

For (the element's data type variable name: Array or collection) {

Loop body

}

Execution procedure: The element is taken out by the subscript of the array and assigned to the variable: int n = nums[i];

Note: The data type of the element must be the same as the data type of the array.

Usage Scenario: The function is slightly inferior to the for loop, and the subscript of the array cannot be directly used in For-each. Used primarily for traversal operations.

eg

Int[] Nums = {10,20,30,40,50};

Method One: Iterating through the array subscript

for (int i=0;i<nums.length;i++) {

int n = nums[i];

SYSTEM.OUT.PRINTLN (n);

}

System.out.println ("*******************");

Method Two: Use For-each to traverse

for (int n:nums) {

SYSTEM.OUT.PRINTLN (n);

}

4 Comprehensive case

Dynamically create arrays based on the number of users entered, and get user input scores, highest score, lowest score and average score

public static void Main (string[] args) {

Double sum=0;//Total

Double avg=0;//Average Score

Double max,min;//highest score and lowest score

System.out.println ("Please enter class Number:");

Scanner input = new Scanner (system.in);

int num = Input.nextint ();//Gets the number of user input

Create an array to hold student scores: data type [] Array name = new data type [length]

Double[] scores = new double[num];//Create an array dynamically based on number of people to save student scores

for (int i=0;i<scores.length;i++) {

System.out.println ("Please enter section" + (i+1) + "Personal score:");

Scores[i]=input.nextdouble ();//Get student scores and save them in an array

}

max = Scores[0]; Suppose the first person's score is the highest score.

min = scores[0]; Suppose the first person's score is the lowest score.

Traverse

for (int i=0;i<scores.length;i++) {

System.out.println (Scores[i]);

sum+=scores[i];//Calculate Total

if (Scores[i]>max) {

max = Scores[i];

}

if (scores[i]<min) {

min = scores[i];

}

}

AVG = sum/scores.length;//calculates the average score

System.out.println ("Highest score:" +max+ ", lowest score:" +min+ ", average score:" +avg ");

}

5 Common algorithms for arrays

5.1 Delete The element that specifies the subscript

Analysis: 1. Move the element after the specified subscript index forward

2. Assign the last element of the array to a value of 0 (0 is the default value for an array element of type int)

public static void Deleteelement (int[] Arr,int index) {

Traverse output before deleting

System.out.println ("The array element before deletion is:");

for (int n:arr) {

System.out.print (n+ "\ t");

}

System.out.println ("");//Line break

Shifts the element after the specified subscript index forward

for (int i=index;i<arr.length-1;i++) {

ARR[I]=ARR[I+1];

}

Assigns the last element of an array to a value of 0

arr[arr.length-1]=0;

System.out.println ("The array element after deletion is:");

for (int n:arr) {

System.out.print (n+ "\ t");

}

}

5.2 Delete The specified element in the array

Analysis:

1) Gets the subscript position of the element in the array based on the value of the element

2) Move the element after the specified subscript index forward

3) assigns the last element of the array to a value of 0 (0 is the default value of an array element of type int)

public static void DeleteElement2 (int[] arr,int element) {

int index=-1;//Save the subscript position of the element

Traverse output before deleting

System.out.println ("The array element before deletion is:");

for (int i=0;i<arr.length;i++) {

Locate the location where the element is located

if (Element==arr[i]) {

Index=i;

}

System.out.print (arr[i]+ "\ t");

}

System.out.println ("");//Line break

Shifts the element after the specified subscript index forward

for (int i=index;i<arr.length-1;i++) {

ARR[I]=ARR[I+1];

}

Assigns the last element of an array to a value of 0

arr[arr.length-1]=0;

System.out.println ("The array element after deletion is:");

for (int n:arr) {

System.out.print (n+ "\ t");

}

}

5.3 Bubble Sort

Principle: Compare the similar two numbers, big backwards, small forward. A maximum value can be determined for each comparison round.

Bubble Sort formula:

N numbers to line up, 22 relatively small front.

Outer loop N-1 (controls the number of wheels to compare);

Inner Loop N-1-i (controls the number of times each round needs to be compared).

eg

public static void sort (int[] arr) {

Outer loop: Controls the number of wheels to compare

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

Inner Loop: Controls the number of times each wheel needs to be compared

for (int j=0;j<arr.length-1-i;j++) {

Swap location

if (Arr[j]>arr[j+1]) {

int temp = Arr[j];

ARR[J]=ARR[J+1];

Arr[j+1]=temp;

}

}

}

}

Iterate through the elements in the array and output

public static void PrintArray (int[] arr) {

for (int n:arr) {

System.out.print (n+ "\ t");

}

System.out.println ();

}

5.4 Finding elements

1) Find by traversal of elements

Queries the target element in the array arr, or returns 1 if the element exists to return its subscript.

public static int Search (int[] arr,int target) {

int index=-1;//The subscript position of the element to find

Traverse

for (int i=0;i<arr.length;i++) {

if (arr[i]==target) {//Comparison

Index=i;

Break

}

}

return index;

}

2) Binary Method search

Premise: the array to be searched must be ordered (in order of size)

Principle: Compare the lookup element to the intermediate element in the array.

If the value is smaller than the middle element, look in the left half

If the value is larger than the middle element, look in the right half

eg

public static int Binnarysearch (int[] Arr,int ele) {

int index=-1;//The subscript position of the element to find in the array

int left=0;//start position

int right=arr.length-1;//End Position

int middle;//Middle Position

while (Left<=right) {

Middle= (Left+right)/2;

if (Arr[middle]==ele) {

Index=middle;

Break

}else if (Arr[middle]>ele) {////middle element value is greater than the element to find, find on left half

right = middle-1;

The value of the}else if (arr[middle]<ele) {///intermediate element is less than the element to find, and the right half finds

left = middle+1;

}

}

return index;

}

6 Java.util.Arrays Tool Class

APIs (application Programming Interface, application programming interfaces) are pre-defined functions designed to provide the ability of applications and developers to access a set of routines based on a piece of software or hardware without having to access the source code. Or understand the details of the internal working mechanism.

In Java, except for the classes and interfaces under the Java.lang package can be used directly, the classes and interfaces under other packages are used, the Import keyword is used to guide the package

Java.util.Arrays class: Provides methods for the following array operations.

Common methods:

Sort (int[] a) sorts the specified array of type int in ascending order of numbers.

ToString (int[] a) returns the string representation (traversal) of the contents of the specified array.

BinarySearch (byte[] A, byte key)

BinarySearch (int[] A, int key): Uses the binary search method to search for the specified array of type int to get the specified value.

Fill (int[] A, int val) assigns the specified int value to each element of the specified array of type int (padding, replacing all elements with 1).

CopyOf (int[] original, int newlength) copies the specified array, intercepts or fills with 0 (if necessary) so that the copy has the specified length.

Copyofrange (int[] original, int from, int to): Copies the specified range of the specified array to a new array. Contains the starting position but does not contain the end position.

....

Access static methods (methods that use the static adornment): Class name. Method Name (..) ; Make a call.

7 Command-line arguments

Role: You can pass parameters (values) for the main method during the execution of a Java command.

Usage: incoming command-line arguments when running Java commands: Java class name "value 1" "Value 2" ...

Note the value of 1, the value of 2: Should be a string type, command-line arguments will have a value of 1, a value of 2 ... Encapsulated into args passed to the main method, multiple parameter values separated by a space, subscript starting from 0

When getting command-line arguments, you need to be aware that subscript cannot go out of bounds, and that the maximum subscript should be the number of parameters-1

8 Variable parameters

Variable parameters (...): A new feature introduced since JDK1.5.

Role: Avoid writing a large number of overloaded methods due to different number of parameters of the same type.

A mutable parameter can represent 0 or more parameters of a specified type.

A mutable parameter can be used only as a parameter of a method (when the method is defined), and a mutable parameter is treated as an array when processed.

And there can be up to 1 mutable parameters in a method, and the position must be placed at the last position of the parameter.

Note: When calling a method with a mutable parameter, the data type must correspond to the type of the mutable parameter.

92-D Arrays

Definition: Each element in an array is an array (array of arrays).

Declaration: Data type [] Array name = new data type [Rows][cols];

eg

Int[][]nums=new int[3][2];

Nums[0][0]=1;

nums[0][1]=2;

...

Note: two-dimensional array declarations need to be specified in the order of high latitude to lower latitudes.

Int[][]nums = new int[3][];//Legal

Int[][]nums = new int[][3];//not valid

Static initialization:

int[][]nums={{1,2},{3,4},{5,6}};

int[][]nums={{1,2},{3,4},{5,6,7}};

Int[][]nums;

nums={{1,2},{3,4},{5,6}};//Error

Example 1: Each class has 3 students, save three classes in the student scores, and calculate the average score.

public static void Test () {

Int[][]scores = new Int[3][3];

Use loops to get student information

Scanner input = new Scanner (system.in);

for (int i=0;i<3;i++) {

int sum=0;//grade of the class

System.out.println ("Please enter the" + (i+1) + "Student grade of the class:");

for (int j=0;j<3;j++) {

Scores[i][j]=input.nextint ();

sum+=scores[i][j];//Calculate Total

}

int AVG = sum/3;//calculates class average score;

System.out.println ("the" + (i+1) + "class average divided into:" +avg);

}

}

Example 2: Calculate the sum of diagonals: The Elements I and J on the diagonal are the same; NUMS[0][0],NUMS[1][1],NUMS[2][2]

public static void Test2 () {

Int[][] nums={{1,2,3},{4,5,6},{7,8,9}};

int sum=0;

for (int i=0;i<3;i++) {

Sum+=nums[i][i];

}

System.out.println ("The sum of the diagonal is:" +sum);

}

5. 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.