Vectorised insertion sort algorithm slower than regular one?

Hello,
My goal is to vectorise a selection sort algorithm so that it performs better than a regular one with nested for loops. Despite extensive efforts, the vectorised version is 2 times slower, and I cannot find a way to fix it.
The regular algorithm was easy:
function sorted = insertionsort(A)
for i = 2:length(A)
value = A(i);
j = i-1;
insert = true;
while insert == true
if A(j) > value
A(j+1) = A(j);
j = j-1;
if j < 1
insert = false;
end
else
insert = false;
end
end
A(j+1) = value;
end
To sort rand(1,5000), it takes about 0.07 seconds. This is the fastest vectorised version I have written:
function sorted = insertsort(a)
% An insertion sort algorithm that orders a vector from smallest to largest
% values. Input any vector.
a % display original
b = zeros(1,length(a)); % preallocate solution vector
for i = 2:length(a)
f = find((a(1:i-1) > a(i)),1);% index of first element larger than a(i)
if ~isempty(f) % only shift elements if a larger one exists
b(f) = a(i); % insert a(i) into place
b(f+1:i) = a(f:i-1); % place larger elements one place to the right
else
b(i) = a(i); % simply insert a(i) into b(i)
end %(if)
a(1:i)=b(1:i); % update sorted section of a for next loop
end %(for)
sorted = a; % display sorted vector
end %(function)
To sort rand(1,5000), on average it takes about 0.12 seconds. More specifically, the find component takes 0.06 seconds while the insertion takes 0.06 seconds. My lecturer said that his vectorised version is 5 times faster, so there must be some shortcut I can make.
Any hints? Thanks.

댓글 수: 2

Stephen23
Stephen23 2017년 4월 5일
편집: Stephen23 2017년 4월 5일
"the vectorised version is 3 times slower"
The times that you give are "0.7 seconds" for the non-vectorized, and "about 0.17 seconds" for the vectorized version.
Surely 0.17 s is faster than 0.7 s ?
Also note that the output should be a or b, and not sort, and that using the name sort is a very very bad idea because that will shadow the very important inbuilt sort function.
Yes, I accidentally put 0.7 instead of 0.07. I have fixed that now. Thank you

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

도움말 센터File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

제품

질문:

2017년 4월 5일

편집:

2017년 4월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by