[Translation] C # data structures and algorithms-Chapter 2 (Part1)

Source: Internet
Author: User

Chapter 2 arrays and arraylists

Arrays are the most common data structures that appear in almost allProgramming Language. Using data in C # is essentially creating an array object of the system. array type. The system. array class is composed of all arrays.AbstractionBase type. It provides a series of methods for sorting and searching.ProgramManually implemented tasks.

An interesting alternative to arrays in C # Is the arraylist class. Arraylist is an array that can automatically add buckets as needed. If you cannot accurately determine the final size of an array or the size of an array changes many times in the life cycle of the program, arraylist is a better choice than array.

In this chapter, we will quickly browse the basic use of arrays in C #, and then turn to a more advanced topic, including copying and cloning arraylist objects, test quality and static methods for using them.

Array Basics

An array is an index-based set of data. Arrays can be both built-in and custom types. In fact, it is possible to regard the data in the array as an object that is the simplest. Data in C # is also an object, because they inherit from the system. array class. Since the array is an instance of the system. array class, you can use the methods and attributes of the system. array class when using arrays.

Declare and initialize an array

The array uses the following syntax declaration:

Type [] array-name;

Type is the data type of an array element, for example:

String[] Names;

The second row is required to initialize the Array (because it is a system. array object) and determine the size of the array.CodeInitialize the declared names array:

Names =New String[10];

And Reserved10Memory space of strings.

When necessary, you can merge the two statements into one row as follows:

String[] Names =New String[10];

Sometimes you want to put the declaration, initialization, and assignment Array Operations in a statement. in C #, you can complete the operation by initializing the list.

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

The list of numbers, called the initialization list, is placed between a pair of curly braces and separated by commas. When using this technique to declare an array, you do not need to specify the number of elements. The Compiler deduce this value from the number of items in the initialization list.

Set and access array elements

Elements stored in the array can be accessed directly or the setvalue method of the array class can be called. Directly access the array elements at the specified position through the index on the left of the value assignment statement.

Names [2] ="Raymond";

Sales [19] = 23123;

The setvalue method provides a more object-oriented way to set the value of an array element. This method accepts two parameters, one index value and one element value.

Names. setvalue ("Raymond", 2 );

Sales. setvalue (23123, 19 );

Array elements can be accessed either through indexes or through the getvalue method. The getvalue method accepts a single parameter-an index value.

Myname = Names [2];

Monthsales = (Int) Sales. getvalue (19 );

It is common to use a for loop to traverse the elements of an array. There are two errors that programmers often make when writing loop statements. One is the upper limit of hard-coded loops (this is an error because if the array is dynamic, its upper limit will change ). Another error is the upper limit of the iteration loop that calls a function to access each loop.

For(IntI = 0; I <= Sales. getupperbound (0); I ++)

Totalsales = totalsales + sales [I];

Methods and attributes for retrieving array metadata

The array class provides several attributes to check the metadata of an array.

    • Length: returns the number of all elements of all dimensions in the array.
    • Getlength: returns the number of elements in the specified dimension of the array.
    • Rank: returns the dimension of the array.
    • GetType: Type of the current array instance.

The Length attribute is used to count the number of elements in a multi-dimensional array. It returns the exact number of elements in the array. In addition, you can use the getupperbound method to get the number of elements in the array by adding 1 to the value.

Length returns the total number of elements in the array. The getlength method counts the number of elements in a single dimension in the array. This method is used together with the rank attribute to adjust the size of the array without the risk of data loss at runtime. This technique will be discussed later in this chapter.

The GetType method is used to specify the data type of an array when you are not sure about the array type. For example, if you pass an array as a parameter to a method. In the following code snippet, a type variable is created. You can use its isarray method to determine whether an object is an array. If the object is an array, the Code returns the Data Type of the array.

Int[] Numbers;

Numbers =New Int[] {0, 1, 2, 3, 4 ,};

TypeArraytype = numbers. GetType ();

If(Arraytype. isarray)

Console. Writeline ("The array type is: {0 }", Arraytype );

Else

Console. Writeline ("Not an array");

Console. Read ();

The GetType method not only returns the array type, but also lets us know that the object is essentially an array. The output of the above Code is as follows:

The array type is: system. int32 []

Square brackets indicate that the object is an array. Pay attention to the format used when displaying data types. We have to do this because we cannot convert the type data to a string to connect to the end of the string to be displayed.

Multi-dimensional array

So far, we have only discussed one array. In C #, Arrays can be up to 32 dimensions, although arrays larger than three dimensions are rare (and confusing ).

To declare a multi-dimensional array, specify the upper bound of each dimension of the array. To declare a two-dimensional array:

Int[,] Grades =New Int[4, 5];

Declares an array consisting of four rows and five columns of elements. A two-dimensional array is often used as a modeling matrix. You can declare a multi-dimensional array without specifying the dimension bounds. To do this, you can use a comma to specify the number of dimensions. For example:

Double[,] Sales;

Declares a two-dimensional array, and vice versa:

Double[,] Sales;

Declares a 3D array. When you declare an array without providing the upper bound of a dimension, you need to use the bounded value to define an array later:

Sales =New Double[4, 5];

Multi-dimensional arrays can be initialized using the initialization list. See the following statement:

Int[,] Grades =New Int[,] {100 },

{, 86 },

{, 89 },

{4,91, 98,79, 88}

};

First, note that the upper bound of the array is not specified. When you use the initialization list to initialize an array. You cannot specify the bounds of arrays. The compiler calculates the upper bound of each dimension based on the data in the initialization list. The initialization list itself is marked with curly brackets, just like each row of the array. Each element in a row is separated by a comma.

Elements accessing multi-dimensional arrays are similar to those accessing one-dimensional arrays. You can use the traditional array access technology.

Grade = grades [2, 2];

Grades [2, 2] = 99;

Or you can use the method of the array class:

Grade = grades. getvalue (2, 2 );

You cannot use the setvalue method to assign values to a multi-dimensional array, because this method only accepts two parameters: A value and a single index. (Original error)

It is common to perform computation on all elements of a multi-dimensional array, although in most cases these operations are based on values stored in array rows or in array columns.

Using the grades array, if each row of the array is a student record, we can calculate the average score of middle school students in this grade. The Code is as follows:

Int[,] Grades =New Int[,] {100 },

{, 86 },

{, 89 },

{4,91, 98,79, 88}

};

 

IntLast_grade = grades. getupperbound (1 );

DoubleAverage = 0.0;

IntTotal;

IntLast_student = grades. getupperbound (0 );

For(IntRow = 0; row <= last_student; row ++)

{

Total = 0;

For(IntCol = 0; Col <= last_grade; Col ++)

Total + = grades [row, Col];

Average = total/last_grade;

Console. Writeline ("Average :"+ Average );

}

Parameter Array

The definition of many methods requires a series of values as parameters. However, in some cases, a variable number of parameter method definitions can be written, which can be constructed using a parameter array.

A parameter array is a list of parameters defined using the Params keyword for a method. The following method definition allows any number of values to be provided to the method as parameters. The return value of the function is the sum of the values passed in to the method.

Static IntSumnums (Params Int[] Nums)

{

IntSum = 0;

For(IntI = 0; I <= nums. getupperbound (0); I ++)

Sum + = Nums [I];

ReturnSUM;

}

This method can be called in the following two ways:

Total = sumnums (1, 2, 3 );

Total = sumnums (1, 2, 3, 4, 5, 6, 7, 8, 9, 10 );

When you use a parameter array in the method definition, parameters in the form of parameter arrays must be placed at the end of the parameter list so that the compiler can correctly process the parameter list. Otherwise, the compiler cannot know the end position of the parameter array element, and cannot obtain the start position of other parameters in the method.

Irregular Array

When you create a multi-dimensional array, you usually create a structure with the same number of elements in each row. For example, the declaration of the following array.

Int[,] Sales =New Int[12, 30];// Sales for each day of each month

This array assumes that each row (month) has the same number of elements (days). However, we know that some months have 30 days, some have 31 days, and one month has29Day. Using the declared array will generate some null elements. This array is not a problem, but using a large array will waste a lot of space.

The solution to this problem is to use an irregular array instead of a two-dimensional array. An irregular array is an array composed of arrays, that is, each row of an array is composed of an array. Each dimension of an irregular array is a one-dimensional array. We call it an "irregular" array because the number of elements in each row may be different. An image of an irregular array will not be a square or a rectangle, and vice versa will have an irregular side.

The declaration method of an irregular array is to place two pairs behind the array variable name.Square brackets. The number in the first square brackets indicates the number of rows in the array, and the second square brackets leave null to leave space for the one-dimensional array in each row. In general, the number of rows is set in the Declaration statement using the initialization list, as follows:

Int[] [] Jarged =New Int[12] [];

This statement looks strange, but you will understand it when you separate it. This staggered array is an integer array with 12 elements, and each element is an integer array. The initialization list is actually used to initialize each row of the array. This indicates that each sub-element of the array 12 elements is initialized as the default value for each element in a row of sub-arrays.

Once an irregular array is declared, each element of the individual row array can be assigned a value. The following code segment assigns a value to an irregular array:

Jarged [0] [0] = 23;

Jarged [0] [1] = 13;

//...

Jarged [7] [5] = 45;

The first square brackets indicate the row number, and the second square brackets indicate the elements of the row array. In the code above, the first line of the statement accesses the first element of the first line of the array, and the second line of the statement accesses the second element of the first line of the array, the third statement accesses the sixth element of the eighth row array.

For example, using an irregular array, the following program creates an array named sales (which records the weekly sales situation in two months) and assigns the sales number to its element, then, we traverse the array to calculate the weekly average sales records for the two months stored in the array.

UsingSystem;

Class Class1

{

Static VoidMain ()

{

Int[] Jan =New Int[31];

Int[] Feb =New Int[29];

//Note: The original text cannot be compiled here, and it must be rewrittenC #3.0.

Int[] [] Sales =New Int[] [] {Jan, Feb };

IntMonth, day, total;

DoubleAverage = 0.0;

Sales [0] [0] = 41;

Sales [0] [1] = 30;

Sales [0] [0] = 41;

Sales [0] [1] = 30;

Sales [0] [2] = 23;

Sales [0] [3] = 34;

Sales [0] [4] = 28;

Sales [0] [5] = 35;

Sales [0] [6] = 45;

Sales [1] [0] = 35;

Sales [1] [1] = 37;

Sales [1] [2] = 32;

Sales [1] [3] = 26;

Sales [1] [4] = 45;

Sales [1] [5] = 38;

Sales [1] [6] = 42;

For(Month = 0; month <= 1; month ++)

{

Total = 0;

For(Day = 0; day <= 6; day ++)

{

Total + = Sales [month] [Day];

}

Average = total/7;

Console. Writeline ("Average sales for month :"+ Month +":"+ Average );

}

}

}

 

Next we will introduce the translation part.ArraylistClass, rarely involved in this bookC #2.0After finishing this book, I will add the generic content according to the corresponding sections and use some programs.C #3.0Implement it again.

 

 

 

 

 

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.