Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Finding the maximum of an array without using a loop  RSS feed

 
Keshini Weerasuriya
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi.. Is thr any way of finding the maximum and minimum of an array without using any loops, or if conditions??

Tnx..
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could sort the array and get the first/last value, though the Arrays.sort() stuff will ultimately be using loops and conditions.
[ October 06, 2006: Message edited by: Paul Sturrock ]
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is pretty much impossible without at least one loop and at least one if condition (maybe two) inside the loop. Or maybe a ternatry operator instead of an if, but the difference seems immaterial. You could hide the loop and conditions by putting them in a separate method - or by calling a pre-existing method such as Arrays.sort() as Paul suggests. But the loop will have to exist somewhere, regardless.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12541
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
think about it in non-programming terms.

How would YOU, by hand, find the largest value in a list of numbers? you'd have to look at each and every number.

if you don't know how many numbers there are, you have to keep looking until you run out.

if you DO know the exact number, you could hard-code your java to say

biggest = element 0;
if element 1 > biggest, biggest = element 1;
if element 2 > biggest, biggest = element 2;
...
if element x > biggest, biggest = element x;

this is not practical if the array has hundreds of elements, or you want the size to dynamically change, but it does allow you to avoid a loop.
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One way could be inserting the items in order into the array, this way you simply get the first and the last item of the array when you want to find the maximum and the minimum.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If this is a trick question or a geek challenge to not use a loop or an if test, I bet you could.

Do you know another way to work over a set of things besides a loop? Like, what would you use for a tree? Is there a way other than "if a>b" to get the larger or smaller of two values?
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!