简体   繁体   中英

Retrieving the highest number in an array recursively in C#?

如何在C#中递归地检索数组中的最高数字?

Right now you're probably thinking that we're mean for not giving you the answer -- and I admit that I have the answer written down and part of me wants to give it to you, even.

Programming is all about finding the solutions to problems yourself. When you're hired as a programmer, you may have other people to lean on, but they've all got their own problems, and you'll need to be able to pull your own weight.

Recursion (in an oversimplifed answer) means to call the same operation over and over until the result is produced. That means you need in every recursive operation, you need to know (at least) two things:

  1. What you're looking for
  2. What you've found so far

The 'What you're looking for' is the termination condition. Once you find that, all work can stop and you can go home.

The 'what you've found so far' is how you know what've you've checked so you don't retread old ground.

So what do you need to know in order to find the highest value in an array recursively?

  1. The contents of the Array.
  2. The highest number you've found so far.
  3. Have you already looked at this part of the Array? (Why look through it again?)

That would produce a method signature that looks like:

public int GetHighestNumber(int[] array, int highestNumberFound, int lastIndexChecked);

Once you're inside the array, you've got to do the following:

  1. Iterate through the array
  2. Stop when you find a value that is higher than the highestNumberFound
  3. Call GetHighestNumber again with the new highestNumberFound and lastIndexChecked updated.
  4. When there are no more 'higher' numbers, then return the highest number found.

I realize it sounds trite, but learning this stuff on your own will make you a better programmer.

If you want to be a professional programmer, you have got to learn this stuff on your own.

If you don't want to be a professional programmer, then drop the course and do something you love.

Here's just a hint (taking int[] as an example):

public int FindMax(int[] array, int indexSoFar, int maxSoFar)

Think about:

  • The start conditions
  • The termination conditions
  • How you move through the array recursively

Reason of EDIT: Didnt want to spoil the answere. Greetings.

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