The classic question of finding the maximum value and its position in the array.

Source: Internet
Author: User

I attended an interview with a logistics company last year and was asked this classic simple question that I did not solve.

It is an array of 100 real numbers, and the maximum value and position in the array are obtained.

Looking back, it's simple. This is what we learned in the first lesson of data structure. Who told me to fall asleep?

The idea of solving the problem is to use an array of 100 to store the location of the maximum value, because the maximum value may have multiple.

Then, traverse the array. All those with a larger position than posion are converted to posion, and set the initial position of the same maximum value of the position array to 1 (because the new one is the largest ). if the maximum value is the same, the location is placed in the array where the maximum value is stored in sequence.

Final output.

Now, let's write down its c # implementation. If there is anything imperfect, please do not mean your bricks and eggs. Thank you.

Code
1 class Program
2 {
3 static void Main (string [] args)
4 {
5 Random r = new Random (10000 );
6 double [] rValues = new double [100];
7
8 for (int I = 0; I <100; I ++)
9 {
10 rValues [I] = r. Next (100 );
11 Console. WriteLine (rValues [I]);
12}
13
14 int [] p = new int [100]; // store all the maximum values
15 int position = 0; // the location where the maximum value is stored
16 int j = 1; // the location where the maximum value is stored
17
18 for (int I = 1; I <100; I ++)
19 {
20 if (rValues [I]> rValues [position])
21 {
22 position = I;
23 j = 1;
24}
25 else if (rValues [I] = rValues [position])
26 {
27 p [j ++] = I;
28}
29}
30
31 p [0] = position;
32
33 if (j <100)
34 {
35 p [j] =-1;
36}
37
38 Console. WriteLine ("maximum value" + rValues [position]);
39
40 Console. WriteLine ("the maximum value is :");
41
42 for (int I = 0; I <100; I ++)
43 {
44
45 if (p [I] =-1)
46 break;
47 Console. WriteLine (p [I] + 1 );
48}
49 Console. ReadLine ();
50
51}
52}

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.