MATLAB实现堆排序算法
时间: 2023-11-07 17:24:31 浏览: 84
matlab.rar_matlab_matlab堆排序_refer69z
function heapSort(A)
%HEAPSORT Sorts an array in ascending order using the heap sort algorithm.
% A: input array to be sorted
% Get the length of the array
n = length(A);
% Build a max heap using the input array
for i = floor(n/2):-1:1
A = maxHeapify(A, i, n);
end
% Extract the maximum element from the heap and place it at the end of the
% array. Then rebuild the heap with the remaining elements.
for i = n:-1:2
temp = A(1);
A(1) = A(i);
A(i) = temp;
n = n - 1;
A = maxHeapify(A, 1, n);
end
% Display the sorted array
disp(A);
end
function A = maxHeapify(A, i, n)
%MAXHEAPIFY Maintains the max heap property by recursively adjusting the
%elements in the heap.
% A: input array that represents the heap
% i: index of the element to be adjusted
% n: size of the heap
% Get the left and right child indices of the element at index i
left = 2*i;
right = 2*i + 1;
% Find the index of the largest element among A(i), A(left), and A(right)
if left <= n && A(left) > A(i)
largest = left;
else
largest = i;
end
if right <= n && A(right) > A(largest)
largest = right;
end
% If the largest element is not the element at index i, swap the two elements
% and recursively adjust the elements in the heap.
if largest ~= i
temp = A(i);
A(i) = A(largest);
A(largest) = temp;
A = maxHeapify(A, largest, n);
end
end
阅读全文