Thread Subject: the bug of my heap sort program ?

Subject: the bug of my heap sort program ?

From: Jin

Date: 16 Nov, 2009 03:34:02

Message: 1 of 2

three functions, min-heapify, buildheap, heapsort in total, please help , thanks



function [ A ] =heapify(A,i)
%UNTITLED4 Summary of thisfunction goes here
%
Detailed explanation goes here
l=2*i;
r=2*i+1;
if l<=length(A) &&A(l)< A(i)
min=l;
else min=i;
end
if r<=length(A) &&A(r)<A(min)
min=r;
end
if min ~=i
temp=A(min);
A(min)=A(i);
A(i)=temp;
heapify(A,min);
end
end


function [ A ] =buildheap( A )
%UNTITLED6 Summary of thisfunction goes here
%
Detailed explanation goes here
heapsize=length(A);
for i=floor(heapsize/2):-1:1
heapify(A,i);
end
end


function
[A]=heapsort( A )
%UNTITLED7 Summary of thisfunction goes here
%
Detailed explanation goes here
A=buildheap(A);
heapsize=length(A);
for i=length(A):-1:2
temp=A(i);
A(1)=temp;
A(i)=A(1);
heapsize=heapsize-1;
heapify(A,1);
end
end

Subject: the bug of my heap sort program ?

From: Darren Rowland

Date: 16 Nov, 2009 05:24:01

Message: 2 of 2

"Jin " <hj_suzhou@hotmail.com> wrote in message <hdqh7a$p60$1@fred.mathworks.com>...
> three functions, min-heapify, buildheap, heapsort in total, please help , thanks
>
>
>
> function [ A ] =heapify(A,i)
> %UNTITLED4 Summary of thisfunction goes here
> %
> Detailed explanation goes here
> l=2*i;
> r=2*i+1;
> if l<=length(A) &&A(l)< A(i)
> min=l;
> else min=i;
> end
> if r<=length(A) &&A(r)<A(min)
> min=r;
> end
> if min ~=i
> temp=A(min);
> A(min)=A(i);
> A(i)=temp;
> heapify(A,min);
> end
> end
>
>
> function [ A ] =buildheap( A )
> %UNTITLED6 Summary of thisfunction goes here
> %
> Detailed explanation goes here
> heapsize=length(A);
> for i=floor(heapsize/2):-1:1
> heapify(A,i);
> end
> end
>
>
> function
> [A]=heapsort( A )
> %UNTITLED7 Summary of thisfunction goes here
> %
> Detailed explanation goes here
> A=buildheap(A);
> heapsize=length(A);
> for i=length(A):-1:2
> temp=A(i);
> A(1)=temp;
> A(i)=A(1);
> heapsize=heapsize-1;
> heapify(A,1);
> end
> end

Jin,
could you specify what makes you think that the code has a bug, perhaps you can show a short example where the result is not in agreement with your expectation.

Another thread which may give you some ideas is located here
http://www.mathworks.com/matlabcentral/newsreader/view_thread/244840

Darren

Tags for this Thread

Add a New Tag:

Separated by commas
Ex.: root locus, bode

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

rssFeed for this Thread

Contact us at files@mathworks.com