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 个评论

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.

请先登录,再进行评论。

 采纳的回答

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 个评论

"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.

请先登录,再进行评论。

更多回答(0 个)

类别

在 帮助中心 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by