C ++ arrays and algorithmsms

zhaozj2021-02-17  50

C Arrays and Algorithmsby Steve Donovan, From The Book C by Example: "Underc" Learning EditionFeb 08, 2002

In this sample chapter, Steve Donovan discusses how to declare, initialize, and use arrays; how to search for particular values ​​and how to sort arrays;. And how to use the standard containers, including vectors, lists, and maps This article is provided Courtesy of que. This Sample Chapter is Excerpted from C by Example: "Underc" Learning Edition, by Steve Donovan.

So far we have discussed the core arithmetic and logical operations of C , as well as features such as strings and input / output that are part of the standard library. In the case study in Chapter 2, "Functions and Control Statements," we hit . some limitations of basic C to pass a number of integers as a parameter, we were forced to write them as a string there are two problems with this;. first, there is no guarantee that these are all valid integers, and second, this would be very inefficient for really large lists of integers. That case study also depends heavily on having everything like ID lists in the correct order, but we can not control the world, and often things happen in an order other than what we plan, so we can not insist on sorted lists. C provides a basic built-in way to set up tables of numbers or objects, called arrays. The standard library also provides more sophisticated ways to group items together, called the standard containers. Algorithms are standard procedu res (or recipes) for doing operations such as searching and sorting. I will compare two ways to search tables of values ​​(binary and linear search), and I will introduce the very powerful library of general algorithms in the standard C library. In this Chapter You Will Learn

How to declare, initialize, and use arrays How to search for particular values ​​and how to sort arrays How to use the standard containers, including vectors, lists, and maps Arrays Arrays contain a linear table of values, which must all be of the same type, called the base type. These values ​​are called the array's elements, and any element can be specified by its position in the array, called its index. in this section we will discuss C 's built-in arrays, together with typical array operations like copying and searching. The next section will then look at the standard containers, which are `intelligent 'arrays. Arrays as Tables of Values ​​A C array declaration reserves space for a number of elements. for instance, the following declarations create an array of ints And An Array of Chars:;> int Arr1 [10] ;;! CHAR ARR2 [10];

;> SIZEOF (Arr1);

(int) 40

>> SIZEOF (Arr2);

(Int) 10 You can see in this example that in general, the space occupied by an array is the number of elements multiplied by the size of each element. The number of elements in an array is usually called its dimension, and it can be . any positive constant You can declare more than one array at a time; in the following code, notice that the dimension follows each new array name The dimension of a3 is the expression M * N, which is acceptable because it contains no variables.. You can Mix Regular Variables in As Well, Althought this is not considered a star x as declared here is just a plain double.;> Const INT n = 20, m = 30;

;> Double A1 [6], A2 [N], A3 [M * ​​N], X; You Declare Two-Dimensional Arrays (Which Are Used For Reresenting Tables Or Mathematical Matrixes) with Two Dimensions, Rather Than with a comma-Separate Pair, as in the following example:;> int Table [10] [10]; // not int Table [10,10] !! Initializing arrays you can initialize arrays by useing a list of values ​​Separated by Commas Enclosed in Braces, as in the following declaration of arr. The declaration of names shows how you can optionally leave out the constant in the brackets and let the system work out the dimension from the size of the list. For global declarations, the values ​​in the list must be Constants.; "INT Arr [4] = {10, 5, 6, 1} ;;> String names [] = {" peter "," alice "," james "}

;> Double Interest_Rates []

= {

5.1,

5.6,

6.0,

7.0

}

;> = {1, 2, 3, 4, 5, 6, 7, 8}; you cannot Assign Arrays in The Following Fashion Because C Arrays Are Not Variables. You Also Cannot USE A1 = A2, WHERE BOTH A1 and A2 Are Arrays.;> Arr = {1, 2, 3, 5};

Con 10: Parse Error

CON 10: error in expression You can, however, treat each element of the array as if it is a variable; this is called indexing the array, and the index is often also called a subscript To access the i-th element of arr. You Say Arr [I], WHERE The index I is put in square brackets ([]) Like in Other Languages ​​Such As Pascal. This Expression Can Be Used. The Array INDEX GoES from 0 to One Less Than Using the definitions of arr and name from the preceding examples, you can say the folload:;> arr [0];

(int & 10

;> Arr [3];

(int & 1

;> Arr [0] 2 * Arr [3];

(int) 12

;> Arr [2] = 2; (int &) 2

;> Names [2] "brown";

(String) `James Brown 'You CAN Make Constant Arrays That Cannot Be Written to Afterward:;> Const Int Ac [] = {10, 2, 4};

;> AC [2] = 2;

Con 71: Can't Assign To a const type there is the no from 0 to n-1 (not 1 to n), and there is no bounds checking whatsoever with arrays. Thereforefor ., if you write past the end of an array, the value will probably go somewhere else In the following case, we have changed the value of var, (which was an innocent bystander) by forgetting both rules:;> int a1 [2 ];

;> int var;

;> A1 [2] = 5;

(INT &) 5

;> var;

(int) VAR = 5

Note

The Fact That C Arrays Always Begin At 0 Is A Benefit. In Some Other Languages, You Can Change The Start Value by a Global Setting.

Note

Running over the end of an array is particularly bad if the array is declared local to a function, and on most systems, this will crash the program badly. The first C program I ever wrote did this, and my DOS machine went down in flames . Up to then I had trained on Pascal, which slaps you on the wrist if you exceed array bounds, but it does not amputate the whole hand. you may regard this as dumb and dangerous behavior, and many would agree with you, but C Was Designed to Be Fast and Somewhat Reckless.

You initialize most arrays by using a for loop for loops naturally go from 0 to n-1, as required This code is equivalent to the initialization of the array numbers from an earlier example in this chapter:;..> For (int i = 0; i <8; i ) numbers [i] = i 1;. Arrays make possible code that otherwise would require big ugly switch statements Consider the problem of starting with a date in International Standards Organization (ISO) form, and working out THE DAY Number (Counting from January 1). One Solution Begins Like this and Would Require Quite a Bit More Tedious Coding: Int Days = Days (Date); Switch (Month) {// Runs from 1 to 12

Case 2: days = 31; Break;

Case 3: Days = 61; Break;

....

} Another solution would be to initialize an array with the lengths of the months and then generate a running sum Thereafter, you could use just one line Here's how you would implement this solution:;..> Int days_per_month [] = {0,31 28, 31, 30, 31, 31, 30, 31, 30, 31};

;> int days_upto_month [13];

;> int SUM = 0;

; int days_upto_month [0] = 0;

;> for (int i = 1; i <= 12; i )

Days_upto_month [i] = days_upto_month [i-1] days_per_month [i];

;> Int days = days_upto_month [month (day)] day; Passing Arrays to Functions You can pass an array to a function, by declaring an array argument with an empty dimension You usually have to pass the size as another argument because there. IS NO SIZE INFORMATION IN C / C Arrays. The advantage of this is what of the following function can be passed Any Array of INTS: Void Show_arr (int Arr [], INT N)

{

For (int i = 0; i

Cout << Endl;

;> Show_arr (Numbers, 8);

1 2 3 4 5 6 7 8 However, you can not pass this function an array of doubles. The following error message means that the compiler failed to match the actual argument (double []) with the formal argument (which was int []) :;> Double DD [] = {1.2, 3.4, 1.2};

;> show_arr (dd, 3);

CON 28:.. Could not match void show_arr (double [], const int); A double value is organized completely differently from an int type If the compiler allowed you to pass an array of doubles, you would get very odd integers displayed On the other hand, simply passing a double value is not much trouble in C ; the compiler sensibly converts the double to an integer and gives you a mild warning that this will involve a loss of precision This difference between passing a double value and passing an. array of doubles exists because in C , ordinary variables (that is, scalars) are passed by value; they are actually copied into the formal argument Arrays, on the other hand, are passed by reference This difference is similar to the difference between.. mailing someone his or her own copy of a document and telling the person where to find it on a network. An interesting result of being able to pass arrays by reference is that you can change an array's elements within a function. (If you altered the. Document on the network, this would change that document for all readers) The following small function modifies the first element of its array argument:;> void modify_array (int arr []) {arr [0] = 777;}

;> Modify_Array (Numbers);

;> Show_arr (Numbers, 8);

777 2 3 4 5 6 7 8 What if you did not want the array to be (accidently) modified? This was always an issue with C, but C has a number of solutions. One solution is to use the standard library's vector class ., which we will discuss later in this chapter Another good solution is to make the array parameter const, as in the following example, so that it is impossible to modify the parameter within the function: void just_looking (const int arr []) { COUT << arr [0] << endl;

} A const parameter is a promise from the function to the rest of the program: "Pass me Data, And i shavert." It's as if i tell you where to find the document on the server, But Make . it read-only Reading Arrays Data arrays are commonly read from files Because arrays are passed by reference, it is easy to write a function to do this job The following example uses a few new shortcuts:.. int read_arr (string file, int Arr [], int MAX_N)

{

IFStream in (file.c_str ());

IF (in.bad ()) Return 0;

INT i = 0;

While (in >> arr [i]) {

i;

IF (i == max_n) returni;

}

Return I;

} In this example, if you initialize the ifstream object in with a filename, that file will be automatically opened. The file is automatically closed when in goes out of scope. Also, the bad () method tells you if the file can not be opened . there is no simple way to work out how many numbers are in any given file, so there's always the danger that you might overrun an array. in functions that modify arrays, it is common for the actual allocated array size to be passed. This function reads up to max_n numbers and will exit the file read loop if there are more numbers; it will return the number of values ​​read, which is one plus the last index Writing out arrays to a file is straightforward You can use the remainder.. Operator (%) To Control The Number of Values ​​Written Out Per Line, AS in The Following Example. (i 1)% 6 IS ZERO for i = 5, 11, 17, ...- That IS, THE CONDITION IS TRUE For EVERY SIXTH VALUE. (I Added 1 To i so this supplies for i == 0.) Void Write_arr (stri Ng file, int Arr [], int N) {

OFSTREAM OUT (file.c_str ());

For (int i = 0; i

OUT << arr [i];

IF ((i 1)% 6 == 0) OUT << ENDL;

Else Out << ``;

}

OUT << Endl;

} Searching You will find that you often need to search for a value in a table of numbers. You want to know the index of that value within that table, or even simply whether the value is present. The simplest method is to run along until You Find the value, or key. If you don't find the key Linear_Search (int Arr [], int N, int val)

{

For (int i = 0; i

Return -1;

}

;> linear_search (Numbers, 4);

(int) 3

;> Linear_Search (Numbers, 42);

(Int) -1 This method is fast enough for small tables, but it is not adequate for large tables that need to be processed quickly. A much better method is to use a binary search, but the elements of that table must be in . ascending order to perform a binary search, you first divide the table in two; the key must be either in the first half or the second half you compare the key to the value in the middle;. if the key is less than the middle value, you choose the first half, and if the key is greater than the middle value, you choose the second half. Then you repeat the process, dividing the chosen half into halves and comparing the key, until either the key is equal to the Value or until you cannot Divide The Table Any Further. Here IS A C Example of Performing a Binary Search: Int Bin_Search (int Arr [], int N, int val

{

INT low = 0, high = N-1; // Initially Pick The Whole Range

While (low <= high) {

INT MID = (Low High) / 2; // Average Value ...

IF (Val == Arr [MID]) Return Mid; // Found The Key

IF (Val

Else Low = MID 1; // Pick The Second Half

}

Return -1; // DID NOT FIND THE Key

HOW MUCH FASTER IS A Binary Search Than A Linear Search? Well, IF There Area 1,000 Entries In A Table, A Binary Search Will Take Only About 30 Tries (on Average) To Find The Key. The catch here is what Table MUST . be sorted If it's already sorted, then it seems a good idea to insert any new value in its proper place Finding the place is easy:.. You run along and stop when the key is less than the value The code for finding the position IS Similar To The Code for a Linear Search, But -1 Now Means That The Key Was Larger Than All The EXISTING VALUES AND CAN SIMPLY Be Appended To The Table: Int linear_pos (int Arr [], int n, int val) {

For (int i = 0; i

IF (Arr [I]> VAL) RETURN I;

Return -1;

} Inserting It takes a surprising amount of effort to insert a new value into an array To make space for the new value means moving the rest of the array along For example, consider that inserting 4 into the sequence 1 3 9 11 15..; Linear_pos () Gives An Index of 2 (Becauses 9 IS Greater Than 4). Everything Above That Position Must Be Shifted Up to make room; the Top Line Shows The Array Subscripts: 0 1 2 3 4 5 Subscripts 1 3 | 9 11 15 Before shifting up by one 1 3 xxx 9 11 15After shifting up by one here 'I've shown the sequence Before I've Shown the sequence before and after the shift. we have to put 4 Before Index 2 (That INDEX 2 (That INDEX 2 (That Is, THIRD POSITION). Third Position Up (9 11 15) HAS Got To Move Up One. That IS, THE Shift Involves A [5] = a [4], A [4] = a [3], And A [3] = a [2 ]. We can life set a [2] = 4. in General: void insert_at (int Arr [], int N, int idx, int val)

{

IF (idx == - 1) Arr [n] = val; // append

Else {

For (INT i = n; i> idx; i-)

Arr [i] = arr [i-1];

Arr [idx] = val;}

}

;> INT N = 5;

;> INT POS = linear_pos (Arr, N, 4);

;> INSERT_AT (Arr, N, POS, 4);

;> Show_arr (Arr, N);

1 3 4 9 11 15 Once insert_at () is defined, then it is straightforward to put a new element into an array so that it remains in order. The special case when idx is -1 just involves putting the value at the end. But . generally there will be a lot of shuffling, making insertion much slower than array access Note that this routine breaks the first rule for dealing with arrays: It goes beyond the end of the array and writes to arr [n] for this to work. , the array neseds to have a dimension of at Least N 1. this is a good example of a for loop doing something Different from what you've seen for loops do Before: in this case, the for loop is Going Down from N to idx 1. in tricky cases like this, I encourage you to experiment (that's what UnderC is for.) But nothing beats sitting down with a piece of paper and a pencil. As you can see from the examples in this section, it IsoN't StraightForward to Insert a value Into an array in order. The algorithm for deleting an item is similar to insert_at () and involves shifting to the left; I leave this as an exercise for a rainy afternoon Sorting Sorting a sequence that is not in any order also involves moving a lot of data around The following algorithm is called a bubble sort because the largest numbers ".. Bubble "Up to the Top. It incduDes calls to show_arr () SO That You Can See How The Larger Numbers Move Up and The Smaller NumBers Move Down: Void Bsort (int Arr [], int N)

{

INT I, J;

For (i = 0; i

For (j = i 1; j

IF (Arr [I]> Arr [J]) {// SWAP ARR [i] and arr [j]

Show_arr (Arr, N); // Print Out Array Before Swap

INT TMP = Arr [I];

Arr [i] = arr [j];

Arr [J] = TMP;

}

Show_arr (arr, n); // show sorted array

}

;> int b [] = {55, 10, 2, 3, 6};

;> BSORT (B, 5);

55 10 2 3 6

10 55 2 3 6

2 55 10 3 6

2 10 55 3 6

2 3 55 10 6

2 3 10 55 6

2 3 6 55 10

2 3 6 10 55

转载请注明原文地址:https://www.9cbs.com/read-30095.html

New Post(0)