Day 5: loop problem, array

Source: Internet
Author: User
Tags array definition ranges rounds
  1. Loop Problems
  2. Array
1. Loop Problems

1.1. Loop Problems

1.1.1. Loop Problems

In actual application, when one or more tasks need to be repeated multiple times, consider using loops.

Solution: in the preceding three types of loops (while, do-while, and for), the for loop is generally used most often, while for the for loop structure, make sure to analyze the three parts that need to solve the business:

  1. Initial State of the Loop Variable
  2. Cycle condition
  3. Changes in cyclic Variables

After analyzing the above three parts, the structure of the for statement is also defined. The other problem is that you fill in different

To solve different business problems.

1.1.2. Loop definition ------ "when" Loop

If the business can be converted to "when ...... "In such a sentence, the while statement is preferred. Let's look at the following requirements: if the annual deposit rate is 3% and the principal is 10000, how much is the benefit when the total amount of deposits exceeds 12000?

The analysis of this demand can be transformed into the following understanding: "When the total deposit is less than 12000, the rate increases by 3%, the condition is total <12000, this "when" sentence is implemented with the while statement first, the simple code is as follows:

 
...... While (condition) {total + = (total * 0.03 );}......

 

1.1.3. Loop problem definition ------ "until" Loop

If the business can be converted to "......" In such a sentence, the do-while statement is preferred. Check the following requirements: You must provide and verify the password when verifying your identity. If the password is incorrect, enter the password again. This requirement can be converted into the following understanding: get the password, "until" the input value is 123456, then the condition is! "123456". Equals (inputpwd), such "...... The simple code is as follows:

 
……do {……} while(! ”123456”.equals(inputPwd));……

 

1.1.4. Definition of Loop Problems ------ fixed number of cycles

If you can obtain an exact number of cycles in the business, you can use the for loop to implement it. See the following requirements: calculate the sum of 1-and the sum of 10 Input numbers, input 3 student information, and store 5 course scores ......, The preceding requirements indicate the exact number of cycles, so the for loop is preferred.

2. Array

2.1. What is an array?

First of all, it is clear that arrays are very important.

The IF structure and loop described above solve algorithm problems. So what is an algorithm? The so-called algorithm is a process, like how to get money? Card plug-in, enter the password, enter the amount of money to withdraw, and then confirm. In this process, the first step, the second step, and the judgment or loop are the algorithms.

Nicklaus Wirth, father of Pascal, said a sentence and therefore won the Turing Award. The classic phrase is that the program is: algorithm + data structure, the so-called data structure, simply put, data is stored according to a specific structure. Designing a proper data structure is a prerequisite for solving the problem. The array mentioned today is the most basic and used data structure. Imagine how to store the score of a student and declare an integer variable score to store the score of 20 students? What about storing 50 random numbers? What about storing 10 thousand accounts? Declaring too many variables is obviously cumbersome and is not suitable for overall operations. In this case, you can use the array data structure to solve the problem.

An array is a set of elements of the same data type. array elements are arranged in a linear order. The linear order means that each element has a unique precursor element except the first element; except the last element, each element has a unique successor element ("one followed by one"), which can be indicated by the ordinal number (subscript) of the element's position) mark each element to access (the subscript starts from 0, and the maximum number of elements is-1). The array structure is shown in-2:


Figure 2

It can be seen that a [0] represents 1st elements, and a [1] represents the second element. Assume that the array has five elements, the last element is a [5-1].

2.2. array Definition

2.2.1. Define an array of Basic Types

Syntax for declaring an array: Data Type [] array name = new data type [size]; sample code:

int [] arr = new int[10] ;

 

In the preceding sample code, int [] is an array type, indicating that each element in the array is an int type. arrays are also used to store data in the memory and store a group of data, you also need a reference to it. The reference is arr. Arr is called an array type variable (reference). New is the keyword of a specific declared array, which will be explained in detail later, remember now. The array declaration must have the number of elements. 10 is the number of elements in the array, also known as the array length. To sum up, the key points for defining an array of basic types include:

  1. Exact data type: used to open up space
  2. Overall array name: Used to reference data
  3. "[]", Which cannot be missing

Note that the new keyword is used to define an array. It is precisely because of the new statement that the array is allocated to a specified size (which will be explained in detail later ).

When declaring an array, either int [] arr or Int arr [] can be written. The common method is int [] arr.

The length of the array is not specified when the array is declared (you can see that only int [] is specified when the declaration is made, and no length is specified ), when the new keyword is used to allocate space, you must specify the size of the allocated space (New int [10]).

2.3. array Initialization

2.3.1. initialize the Array

After an array of the basic type (data element is of the basic type) is created, the initial value is set for its array element by default. The initial value of the element is as follows: byte, short, Char, Int, long are 0, float and double are 0.0, and Boolean is false. Note that the default value of the basic type array is emphasized here. In the future, we will introduce the non-basic type of data elements. Its default initial value is different from the basic type.

In the program, you often need to manually set the initial value, which can be initialized at the same time as the array declaration, as shown in the following code:

 
int [ ] arr = { 10,23,30,-10,21 } ;

 

In the code above, the number of elements is the length of the array. However, this method can only be used for initialization during declaration, and cannot be used to declare and assign values first. For example, the following code may cause compilation errors:

 
int [ ] arr;arr = { 10,23,30,-10,21 } ;

 

For declared arrays, You can initialize the array type variables in the following way:

 
int[] arr;arr = new int[]{ 10,23,30,-10,21 };

 

Note: The length cannot be written in [] After new, and the number of elements is the length of the array.

2.4. array access

2.4.1. Get the length of the array

In the program, call the Length attribute of the array to obtain the length of the array, as shown in the following code:

 
Int [] arr = new int [] {3, 6, 8, 9}; int Len = arr. length; system. Out. println ("array length:" + Len );

 

In the above Code, Len is the length of the array, and the output result is: "array length: 4 ".

2.4.2. Accessing array elements through subscript

If you want to access the elements in the array, you need to use the following method. Note that the subscript of the array starts from 0 and ranges from maximum to length-1. The Code is as follows:

 
Int [] arr = new int [] {3rd, 6, 8}; int temp = arr [2]; // get elements, that is, the values of two adjacent elements whose subscripts are 2 and 3. The interaction result is:, 8, 6int temp = arr [2]. arr [2] = arr [3]; arr [3] = temp;

 

2.4.3. Traverse array elements

In practical applications, you often need to perform operations on the entire array. The most common method is to traverse the array elements. Generally, you can select the for loop statement and the loop variable as the subscript to access the array elements, you can access each element in the array. The following code uses the loop method to assign a value of 100 to each element in the array.

 
int[] arr = new int[10];for ( int i = 0 ; i < arr.length ; i ++ ){arr [ i ] = 100;}

 

Note: The variation range of the cyclic counter ranges from 0 to the array length-1. You can write a condition such as "less than the length" to prevent the subscript from exceeding the range ).

The above Code assigns values to array elements in a loop. The following two sections of code output the array element data in a forward and backward order in a loop mode:

 
Int [] arr = new int [5] {10, 20, 30, 40, 50}; // forward Output for (INT I = 0; I <arr. length; I ++) {system. out. println (ARR [I]);} int [] arr = new int [5] {10, 20, 30, 40, 50}; // output in reverse order for (INT I = (ARR. length-1); I> = 0; I--) {system. out. println (ARR [I]);}

 

 

2.5. Copying Arrays

2.5.1. system. arraycopy Method Used for Array Replication

To copy an array, use the system. arraycopy () method. Its structure is as follows:

public static void arraycopy(Object src, int srcPos,Object dest, int destPos, int length)

 

For the meanings of each parameter in the code above, see the following list:

  • SRC: source array
  • Srcpos: Start position in the source array
  • DeST: Target Array
  • Destpos: Start position in the target array
  • Length: Number of array elements to be copied

The following code copies an array:

Int [] A = {10, 20, 30, 40, 50}; int [] a1 = new int [6]; system. arraycopy (A, 1, A1, 0, 4); Result: 20, 30, 40, 50

 

The meaning of the above method can be understood as: copy the four elements of array a starting from subscript 1 to the A1 array, and assign values to the A1 array from the subscript 0. After the program is executed, the A1 value is 20, 30, 40, 50, 0. The interaction result is shown in-3:


Figure-3

2.5.2. The arrays. copyof method is used for Array replication.

The copyof method of the Java. util. arrays class can be used to copy arrays. Its structure is as follows:

Type [] newarray = arrays. copyof (type [] original, int newlength)

 

The example code of the arrays. copyof () method is as follows:

 
int [ ] a = { 10,20,30,40,50 } ;int [ ] a1 = Arrays . copyOf ( a, 6 );

 

After the preceding code is executed, the A1 result is: 10 20 30 40 50 0. The execution process is: declare an integer array, and the array variable name is, assign an initial value of 10 20 30 40 50, declare the integer array A1, copy the data of array A to the A1 array, and set it to 6 lengths, Because array A has only five elements, so the last digit is 0. Therefore, the output result is 10 20 30 40 50 0. The features of the arrays. copyof () method are summarized as follows:

  • The new array is a copy of the original array;
  • If newlength is smaller than the source array, It is intercepted. (You can use the code to demonstrate the effect );
  • If newlength is greater than the source array, it is filled with 0 or null;

2.5.3. "resize" the Array"

The Java syntax stipulates that the length of an array cannot be changed after it is created, which must be clear. The so-called resizing actually refers to creating a larger new array and copying the content of the original array to it. You can use the arrays. copyof () method to easily implement Array Extension. The Code is as follows:

int [ ] a = { 10,20,30,40,50 } ;a = Arrays . copyOf ( a, a.length+1 );

 

After the preceding code is executed, the output data of array a is: 10, 20, 30, 40, 50, 0. In this case, the length of array a is 6, which implements the so-called "expansion ".

2.6. array sorting

2.6.1. Sorting Arrays

There are many algorithms applied to arrays. The most common algorithm is the sorting algorithm. The so-called sorting refers to the re-arrangement of array elements in the order from small to large or from large to small. When the number of array elements is large, the merits and demerits of the sorting algorithm are crucial, because it will directly affect the execution efficiency of the program, the advantages and disadvantages of the sorting algorithm are usually measured by the number of exchanges of array elements in the sorting process.

Common sorting algorithms include insert sorting, Bubble sorting, and quick sorting. We will introduce Bubble Sorting today.

2.6.2. array Bubble Sorting Algorithm

Bubble Sorting is a very classic sorting algorithm. Its sorting principle is: relatively adjacent elements. if it violates the final sequence criterion (from large to small or from small to large ), switch. It can be simplified to understand that the largest (or least) of all elements are found at the last position for the first time and no change is made. The second time, the largest (or least) of all remaining elements are found) is placed in the second to the last position, no change, and so on until the sorting is completed. During the comparison, you can either use the "Sinking" method or the "floating" method.

The Bubble Sorting logic is shown in-1.


Figure-1

The following is a detailed analysis of the above example. The requirement is: the initial sequence is, 50, 86, in ascending order (small before, big after );

For the first round of the first round, 89 compared with 50, the switching position. Results: 50, 89, 86

The second round of the first round, 89 compared with 84, the switching position. Results: 50, 84, 86

In the third round of the first round, 89 and 57 were compared. The result was: 50, 84, 86.

In the fourth round of the first round, 89 compared with 61, the switching position. Results: 50, 84, 20, 86

In the fifth round of the first round, 89 and 20 were compared. The result was: 50, 84, 20, 89, 86.

In the sixth round of the first round, 89 and 86 were compared. The result was: 50, 84, 20, 86, 89.

It will pop up 89, and the current sequence is: 50, 84, 20, 86, 89

For the first time in the second round, the positions of 50 and 84 are not changed.

The second round of the second round, 84 compared with 57, the switching position, Results: 50, 57, 20, 86, 89

In the third round of the second round, 84 compared with 61, the switching position. Results: 50, 57, 20, 86, 89

In the fourth round of the second round, 84 compared with 20, the switching position. Results: 50, 57, 89

The fifth round of the second round, 84 compared with 86, the location is not changed

The sequence 86 appears. The current sequence is: 50, 57, 89.

For the first time in the third round, the positions of 50 and 57 are not changed.

Second round of the third round, 57 compared with 61, the location is not changed

The third round of the third round, 61 compared with 20, the exchange position, Results: 50, 57, 20, 61, 89

The third round and the fourth round, 61 compared with 84, the position is not changed

The sequence 84 appears. The current sequence is: 50, 57, 20, 61, 84,86, 89.

For the first time in the fourth round, the positions of 50 and 57 are not changed.

In the second round of the fourth round, 57 compared with 20, the switching position. Results: 50, 20, 86, 89

The third round of the fourth round, 57 compared with 61, the position is not changed

It will pop up from 61. The current sequence is: 50, 20, 89.

For the first time in the fifth round, 50 and 20 were compared. The result was: 20, 50, 89.

Second time in the fifth round, comparison between 50 and 57, location not changed

57 is popped up. The current sequence is: 20, 50, 89.

For the first time in the sixth round, the positions of 20 and 50 are not changed.

The current sequence is: 20, 50, 57,61, 84,86, 89.

The above analysis summarizes the following points, finds out the rules, and completes the implementation of the bubble algorithm through the program.

  • If the number of array elements is 7, the sorting process requires six rounds, because there is no need to compare one element.
  • If the number of array elements is 7, the number of 1st rounds is 6, the number of 2nd rounds is 5, and so on, the number of 6th rounds is only 1.

Through the above analysis, write the Bubble Sorting Algorithm as follows:

 
    int[] arr = {89,50,84,57,61,20,86};    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]){                int temp = arr[j];                arr[j] = arr[j+1];                arr[j+1] = temp;            }}}

 

2.6.3. The arrays. sort method is used for Array sorting.

The arrays. Sort () method provided by JDK encapsulates the array sorting algorithm, as shown in the following code:

 
int[ ] arr = { 49, 81, 1, 64, 77, 50, 0, 54, 77, 18 };Arrays.sort( arr ) ;for(int i=0; i<arr.length; i++) {    System.out.println(arr[i] );}

 

Analyze the above Code and the output result is: 0 1 18 49 50 54 64 77 77 81. We can see that the arrays. Sort () method achieves ascending order.

Day 5: loop problem, array

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.