MATLAB实现堆排序

clear;clc;close all
x = [4,3,1,6,7,5,2,1,5,6,7,8];
node = floor(length(x)/2);
for i = node : -1 : 1
    x = heap(x, i, length(x));
end
for i = length(x) : -1 : 1
    x([1,i]) = x([i,1]);
    x = heap(x, 1, i-1);
end

function x = heap(x, node, sz)
left = node * 2;   % 左叶子节点
right = node * 2 + 1; % 右叶子节点
max_idx = node;
if left <= sz && x(left) > x(node)
    max_idx = left;
    x([left, node]) = x([node, left]);
end
if right <= sz && x(right) > x(node)
    max_idx = right;
    x([right, node]) = x([node, right]);
end
if max_idx ~= node
    x = heap(x, max_idx, sz);
end
end

 

你可能感兴趣的:(Matlab)