Find Largest & Second Largest Number Index in Array - Ask Algorithm

  • Thread starter Thread starter nenyan
  • Start date Start date
  • Tags Tags
    Algorithm
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 2K views
nenyan
Messages
67
Reaction score
0
a function: can give the index of the largest number in an array. also give the index of the second largest number, and the index of the third and the forth.


such as

a={1,2,3,5,7,99,121,3,2,24,10}
the code can give the result followed:
6,5,9,10

how to make the function?
 
Physics news on Phys.org
eh, I got one

max[4]=-100;
maxIndex[4]=-1;
for i=1:4
for j=a1:an
if aj>maxi
max=aj;
maxindex=j;
end if
end for j
end for i
 
One way would be to use any sort algorithm, but instead of outputting the values to a target array, you give your sort function an array that is the same dimension but contains index information.

So basically you initialize your index array to a = i and then in your sort function swap the values in your index array instead of modifying your values in the actual data array itself.

You can use the above idea with any sort implementation.
 
That's a good idea! Thank you.
chiro said:
One way would be to use any sort algorithm, but instead of outputting the values to a target array, you give your sort function an array that is the same dimension but contains index information.

So basically you initialize your index array to a = i and then in your sort function swap the values in your index array instead of modifying your values in the actual data array itself.

You can use the above idea with any sort implementation.