Use arrays to solve the problem (1). Use arrays to solve the problem.

Source: Internet
Author: User

Use arrays to solve the problem (1). Use arrays to solve the problem.

Arrays are extremely common in programming, and array techniques are often used in non-array scenarios. Therefore, Arrays can be used as an important training place to solve problems with data structures.

I. Basic Knowledge Overview 1. Storage

This is the most basic operation. An array is a set of variables. You can assign values to each variable.

TenIntegerArray [0] = 5; // assign the integer 5 to the first 1st elements of the previously declared Array
Int tenIntegerArray [10] = {1, 2, 3, 6, 12,-57,30987, 0,-287,9}; // assign a specific value to each element in the array
Int tenIntegerArray [10]; for (int I = 0; I <10; I ++) tenIntegerArray [I] =-1; // initialize the 10 elements of an array to-1
2. Copy

To copy an array, you only need to use a loop and a value assignment statement, just like initializing a value.

int tenIntegerArray[10] = {1,2,3,6,12,-57,30987,0,-287,9};int secondArray[10];for(int i = 0;i < 10;i++)    secondArray[i] = tenIntegerArray[i];
3. Extraction and search

In addition to putting values into the array, we also need to be able to extract them from the array.

int num = tenIntegerArray[0];

But it is generally not that simple. We often do not know the location we need. We must search for the array to find the location of a specific value. If the elements in the array do not have a specific order, it is best to perform a linear search, that is, viewing each element from the end of the array until the desired value is found.

Const int ARRAY_SIZE = 10; // array length int intArray [ARRAY_SIZE] = {, 9, 12,-,-57,30987,-287,1}; // array itself int targeValue = 12; // int targePos = 0; // position of the value found in the array while (intArray [targetPos]! = TargeValue) & (targePos <ARRAY_SIZE) // use the ARRAY_SIZE constant to limit the number of iterations of this array. targePos ++;

Sometimes, what we search for is not a fixed value, but a value that has a relationship with other values in the array.

For example, we may want to search for the maximum value in the array. I call the mechanism for completing this task "The King of hills" and use a variable to represent the maximum value found in the array so far. Use a loop to traverse all the elements in the array. Whenever a value greater than the current maximum value is reached, the previous King will be kicked down from the hill and replaced:

Const int ARRAY_SIZE = 10; // array length int intArray [ARRAY_SIZE] = {, 9, 12,-,-57,30987,-287,1 }; // int highestValue = intArray [0]; // when declared, it is assigned the value of the first element in the array for (int I = 1; I <ARRAY_SIZE; I ++) {// loop from the second element of the array if (intArray [I]> highestValue) // compare the current position value with highestValue = intArray [I]; // replace the value of highestValue in due time
4. Sorting

Sort data in a specific order.

Fast and convenient sorting with qsort

To use qsort, you must compile a comparison function. This function is called by the qsort function to compare two elements in the array and determine which one should appear before the sorting sequence. This function should return an integer. The value of the first element is greater than, less than, or equal to the second element. The value of this integer is positive, negative, or zero, respectively. The specific returned value does not matter. It is important that it is greater than, less than or equal to zero. Now, we use qsort to sort an array containing 10 integers. Write the comparison function first:

    int compareFunc(const void * voidA,const void * voidB){        int * intA = (int *)(voidA);        int * intA = (int *)(voidB);        return *intA - *intB;    }

With the comparison function, the following is an example of qsort usage:

    const int ARRAY_SIZE = 10;    int intArray[ARRAY_SIZE] = {87,28,100,78,84,98,75,70,81,68};    qsort(intArray,ARRAY_SIZE,sizeof(int),compareFunc);

However, in some cases, you need to write the sorting code yourself.

I suggest using a sort Insertion Algorithm. The way it works is similar to the way people use cards when playing bridges: one time they grab a card and insert it into their hands. The proper position of the card is maintained in the overall order, and move the remaining cards to reserve space.

The basic implementation of the insert Sorting Algorithm for integer arrays is as follows:

Int start = 0; // The first element in the array int end = ARRAY_SIZE-1; // The last element in the array for (int I = start + 1; I <= end; I ++) {// the outer loop selects the next card to be inserted. It is inserted into a card in ascending order. for (int j = I; j> start & intArray [J-1]> intArray [j]; j --) {// constantly exchange the current value with its previous value, until it reaches the correct position int temp = intArray [J-1]; // swap the current value to the previous position in the array intArray [J-1] = intArray [j]; intArray [j] = temp ;}}
5. calculate statistical data

Similar to the extraction operation. The difference is that the statistical data is calculated based on all values in the array. For example, calculate the average score of a group of students:

    const int ARRAY_SIZE = 10;    int gradeArray[ARRAY_SIZE] = {87,76,100,97,64,83,88,92,74,95};    double sum = 0;    for(int i = 0;i < ARRAY_SIZE;i++)        sum += gradeArray[i];    double arerage = sum / ARRAY_SIZE;

Another simple example is data verification. Suppose there is an array named vendorPayments that contains the double value, indicating the payment to the seller.

 

2. Use arrays to solve the problem: Find the Mode

In statistics, the mode of a group of values is the most common value. Write code, process an array containing the survey data, and determine the mode of the dataset. In this array, the investigator uses 1 ~ A number in the range of 10 represents the answer to a question. If we have multiple modes, we can choose one of them.

1. First, observe an example array and its length constant:
    const int ARRAY_SIZE = 12;    int surveyData[ARRAY_SIZE] = {4,7,3,8,9,7,3,9,9,3,3,10};

After simplification:

    int surveyData[ARRAY_SIZE] = {4,7,7,9,9,9,8,3,3,3,3,10};

Now, two 7 s appear together, and three 9 s appear together. After the data is arranged in this way, we can linearly process the array and find the mode.

2. Let's write some pseudo code first: (the so-called pseudo code is a statement similar to the program code. It can remind us what task should we complete when writing each statement)
Int mostFrequent = ?; Int highestFrequency = ?; Int currentFrequency = 0; for (int I = 0; I <ARRAY_SIZE; I ++) {// process the array currentFrequency ++; // The value of the variable that counts the number of occurrences of the current value plus 1 if (surveyData [I] is last occurrence of a value) {// check, check whether the last occurrence of if (currentFrequency> highestFrequency) is reached for a specific value {// if yes, this value becomes the new most common value highestFrequency = currentFrequency; mostFrequent = surveyData [I];} currentFrequency = 0; // Since the next read value will be the first time the new value appears, we reset the counter to 0 }}
, 3. Let's go back to the logic of the if statement temporarily skipped.

How can we know the last appearance of a value in the array?

Because the values in the array are already grouped, when the next value in the array is different from the current value (surveyData [I] is not equal to surveyData [I + 1]), we can see that this is the last appearance of the current value.

4. Now you can consider the initial value of the variable.

Currently, the "most common" value is represented by two variables. mostFrequent indicates the value itself, and highestFrequency indicates the number of occurrences of the value. If you can initialize mostFrequent to the first value in the array and initialize highestFrequency to the number of occurrences of this value in the array, it is certainly better, But before entering the loop and counting, there is no way to determine the number of occurrences of the first value. At this point, we may think that no matter how many times the first value appears, it is always greater than zero. Therefore, we initialize the highestFrequency variable value to zero. When we reach the last appearance of the first value, this code will replace the value of the highestFrequency variable with the number of occurrences of the first value. The complete code is as follows:

    int mostFrequent;    int highestFrequency = 0;    int currentFrequency = 0;    for(int i = 0;i < ARRAY_SIZE;i++){          currentFrequency++;          //if(surveyData[i] is last occurrence of a value)        if(i == ARRAY_SIZE - 1 || surveyData[i] != surveyData[i+1]){              if(currentFrequency > highestFrequency){                   highestFrequency = currentFrequency;                mostFrequent = surveyData[i];            }            currentFrequency = 0;          }    }

To sort arrays, we only need to call qsort at the beginning of the Code:

    qosrt(surveyData,ARRAY_SIZE,sizeof(int),comareFunc);
5. refactoring

Is there such an array that we can apply the "Find the maximum value" method to get the mode of the survey data? The answer is yes.

The array we need is the column chart of the surveyData array. A bar chart is a chart that shows the frequency of occurrence of different data in the underlying data. The array we need represents the data of this column chart. In other words, we will store the occurrence frequency of each value ranging from 1 to 10 in an array with a length of 10 elements in the surveyData array. The following code creates a bar chart:

Const int MAX_RESPONSE = 10; int histogram [MAX _ RESPONSE]; // an array for storing bar chart data (int I = 0; I <MAX_RESPONSE; I ++) {// initialize each value of the array to 0 histogram [I] = 0 ;}for (int I = 0; I <ARRAY_SIZE; I ++) {// count the occurrences of each value in the surveyData array histogram [surveyData [I]-1] ++ ;}

(Note: The bar chart code is compiled independently, so that you can test it separately .)

After testing the above code, you can now search for the maximum value of the histogram array:

Int mostFrequent = 0; // initialization for (int I = 1; I <MAX_RESPONSE; I ++) {if (histogram [I]> histogram [mostFrequent]) mostFrequent = I;} mostFrequent ++;

Note: mostFrequent is the position of the maximum value in the histogram array, rather than the maximum value. Therefore, we initialize it to 0 instead of the value of location [0]. In the if statement, we compare it with histogram [mostFrequent] instead of mostFrequent itself. When finding a larger value, we assign mostFrequent to 1 instead of histogram [I]. Finally, we increase the value of mostFrequent by 1, which is the opposite of the operation of subtracting 1 from the previous loop to obtain the correct array position. For example, if we tell mostFrequent that the maximum array location is 5, the most common item in the survey data is 6.

 

Summary: The complexity of the Bar Chart solution increases linearly with the number of elements in the SurveyData array, which is the best result we can expect. Therefore, it is a better solution than the original sorting method.

Related Article

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.