devolver el índice en una ordenación por inserción
Frecuentes
Visto 1,226 veces
0
I want to know how to return the indices of the original elements in the insertion sort algorithm such as the function [B,IX] = sort(A,...)
en matlab.
El algoritmo es:
function list = insertionSort(list)
for i = (2:numel(list))
value = list(i);
j = i - 1;
while (j >= 1) && (list(j) > value)
list(j+1) = list(j);
j = j-1;
end
list(j+1) = value;
end %for
end %insertionSort
Quiero una función [list indx]= insSort(list)
to return the sorted elements with its original indices.
1 Respuestas
0
Hope this isn't homework.
function [ind, list] = insertionSort(list)
ind = [1:length(list)]'; % build list of indicies
for i = (2:numel(list))
value = list(i);
j = i - 1;
while (j >= 1) && (list(j) > value)
list(j+1) = list(j);
ind(j+1) = ind(j); % copy index when you shift
j = j-1;
end
list(j+1) = value;
ind(j+1) = i; % write final index location
end
end
respondido 27 nov., 13:06
It's not. Thank you for your help. - A3B2
also, i didnt check the speed of this with any large data sets, so make sure you profile it. sorting large data sets efficently is kind of a black art - atípicos
it works well and of course the algorithm becomes very slow while sorting the last part of the data :) - A3B2
yeah, unless you are tailoring your function to a very specific dataset, its hard to beat the efficency of profesionally coded sort algorithms. - atípicos
that's right !last version of sort in matlab implements 3 level sorting as in that link mathworks.com/company/newsletters/articles/… as MrAzzaman mentioned in a previous comment - A3B2
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas matlab sorting or haz tu propia pregunta.
If you don't mind me asking, why are you writing your own sort algorithm when MATLABs
sort
method will be faster pretty much 100% of the time? - MrAzzamansort method in matlab is depending on the quick sort which is slower than insertion sort in a nearly ordered data which is the case of my data. - A3B2
Debes leer este MATLAB blog post. As far as I can tell, MATLAB already drops down to an insert sort after a certain point, so I would be surprised if a pure insert-sort would be faster. Not to mention the fact that
sort
is native compiled code, which is going to be very hard to beat with just MATLAB code. - MrAzzamanyou are right, my claim was based on the info here [link] (sorting-algorithms.com) without coding,,, but after trying many samples the built-in sort in matlab is faster than the insertion even in the case of nearly sorted data..... Thank you for your valuable comments :) - A3B2