How to find 3 maximum element in array and their indices without sorting

Hi everybody
I have an array like this(its data type is double):
a = {1,4,2,7,1,2,9,11,4,3,1,7,12,3,5,6,2,1}
I want to return 3 or more maximum element with their indices without any changes in the original form of "a" (like sorting it)
thanks in advance

3 Comments

You're asking to find x1, x2, x3 belonging to a such that:
x1 >= x2 >= x3 >= all other xn
You can call it whatever, but mathematically it is imposing an ordering on the set and that is called sorting.
You may be able to achieve this without calling sort but it is sorting.
I dont want to sort this array and in addition I need their indices in the original array.
so do you have any solution for this problem?
thanks in advance
"I dont want to sort this array "
Yes you do. Sorting means putting those values into order. You want to select some depending on their order, ergo you want to sort the values. You are contradicting yourself.

Sign in to comment.

 Accepted Answer

You can call max three times, each time removing the element you found, but see my comment above, you are effectively sorting the set
a = [1,4,2,7,1,2,9,11,4,3,1,7,12,3,5,6,2,1];
elemrequired = 3;
sorteda = zeros(1, elemrequired)
sortedindices = zeros(1, elemrequired)
for iter = 1:elemrequired
[sorteda(iter), sortedindices(iter)] = max(a);
a(sortedindices(iter)) = nan;
end
You are effectively emulating the first elemrequired steps of an inefficient sort algorithm (selection sort).
This is of course simpler, and probably faster:
a = [1,4,2,7,1,2,9,11,4,3,1,7,12,3,5,6,2,1];
elemrequired = 3;
[sorteda, sortedindices] = sort(a, 'descend');
sorteda = sorteda(1:elemrequired)
sortedindices = sortedindices(1:elemrequired)

1 Comment

"I dont want to sort this array" "I want to return 3 or more maximum element": I'll repeat: you can call it whatever you want, finding 3 or more maximum element, mathematically, is the definition of sorting.
"I need their indices in the original array": I've edited my answer to return that. The code does not use sort but is in effect reproducing the first steps of a selection sort. There is no way around it.

Sign in to comment.

More Answers (0)

Categories

Asked:

mhm
on 21 Jan 2016

Commented:

on 21 Jan 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!