简体   繁体   中英

How to find the biggest number in an array

I have an array with a size that I dont know(mostly a size of a 10), that most of it has 1's and 2's, but sometimes 3's and 4's... I cant buble sort, because the order is importhan, but other then that, I can do everything

Thanks :)

Iterate over the array until you hit your break condition.

While iterating (use the for or while loop), remember the highest value so far and compare against current.

I don't have access to a compiler that supports this right now, but here's a concise example of how to do it in C++11:

#include <iostream>

constexpr int array[10] = { 1, 0, 2, 3, 0, 2, 7, 1, 9, 2 };

template<int maxest, int index>
struct find_biggest_r {
  enum { value = find_biggest_r<(array[index] > maxest ? array[index]:maxest),index-1>::value };
};

template<int maxest>
struct find_biggest_r<maxest,0> {
 enum { value = (array[0] > maxest ? array[0] : maxest) };
};

template<int index>
struct find_biggest {
  enum { value = find_biggest_r<array[index],index-1>::value };
};

int main()
{
    std::cout << find_biggest<9>::value;
}

//

Now that I'm done trolling, in C, you would do:

int array[4] = { 2, 1, 0, 2 };
int biggest = array[0];
for (int i = 1; i < 4; i++) { // we've already used array[0] so we start at array[1]
  if (array[i] > biggest) biggest = array[i];
}

I will give only the pseudocode

max := array[0];

for i = 1 to size
    if(array[i] > max)
     {
        max := array[i]
     }

start traversing the array in a for loop. Take a variable and by default put the first element in it and assume as the highest. while you traverse,when ever you find an element greater than the value in the variable just replace it. at the end of the loop the value contains the highest number.

You can try this:-

int max = array[0];    
for (int j = 1 to size)
{
    if(array[j] > max)
     {
        max = array[j];
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM