[Closed] search greatest number
I have very simple question but I’m out of ideas.
I have different arrays with numbers:
In example array : numbers=#(1,33,21,91,29,32,17)
I would like to know which item in my array is the greatest without sorting it, in this case its item number 4, but how to check it. Any ideas? I guess is super simple but somehow simplest task give me headache.
Thank you so much, I spent so much time to figure this out. Thanks one more time.
another way of doing it
(
fn Comparefn a b = ( if a.val < b.val then 1 else if a.val > b.val then -1 else 0; )
struct IndexedItem (val,i)
numbers = #(32,44,52,1,2,44,55,74,21,667,88,73,4)
inumbers = for i = 1 to numbers.count collect IndexedItem numbers[i] i;
qsort inumbers Comparefn;
inumbers[1].i;
)
another way of doing it, that may be more efficient if say you need the next highest etc or if you need to search for a particular value and the data sets are large
(
fn Comparefn a b = ( if a.val < b.val then 1 else if a.val > b.val then -1 else 0; )
struct IndexedItem (val,i)
numbers = #(32,44,52,1,2,44,55,74,21,667,88,73,4)
inumbers = for i = 1 to numbers.count collect IndexedItem numbers[i] i;
qsort inumbers Comparefn;
(bsearch (IndexedItem 44 0) inumbers Comparefn).i
)
Since you are probably just starting out, the primitive manual “textbook” way of solving this would have been:
numbers=#(1,33,21,91,29,32,17)
maxVal = numbers[1]
maxId = 1
for i = 1 to numbers.count do
if numbers[i] > maxVal then
(
maxVal = numbers[i]
maxId = i
)
format "
Element #% was the largest: %. " maxId maxVal
You should take into consideration that in the case of more than one index containing the highest number, some of the proposed solutions will return the first and some will return the last.