Ask an algorithm

  • Thread starter nenyan
  • Start date
  • #1
67
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?
 

Answers and Replies

  • #2
67
0
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
 
  • #3
chiro
Science Advisor
4,797
133
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.
 
  • #4
67
0
That's a good idea! Thank you.
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.
 

Related Threads on Ask an algorithm

  • Last Post
Replies
2
Views
3K
  • Last Post
Replies
6
Views
2K
Replies
18
Views
3K
Replies
6
Views
3K
  • Last Post
Replies
1
Views
4K
Replies
4
Views
2K
  • Last Post
Replies
2
Views
6K
  • Last Post
Replies
3
Views
2K
  • Last Post
Replies
2
Views
3K
  • Last Post
Replies
2
Views
2K
Top