赞
踩
function result = mergeSort(arr) n = length(arr); if n <= 1 result = arr; return; end mid = floor(n / 2); leftArr = arr(1:mid); rightArr = arr(mid+1:end); leftArr = mergeSort(leftArr); rightArr = mergeSort(rightArr); result = merge(leftArr, rightArr); end function result = merge(leftArr, rightArr) i = 1; j = 1; m = length(leftArr); n = length(rightArr); result = []; while i <= m && j <= n if leftArr(i) <= rightArr(j) result(end+1) = leftArr(i); i = i + 1; else result(end+1) = rightArr(j); j = j + 1; end end if i <= m result = [result, leftArr(i:end)]; end if j <= n result = [result, rightArr(j:end)]; end end
arr = [5, 2, 8, 3, 1, 6, 9, 7, 4];
result = mergeSort(arr);
disp(result);
输出结果为:[1, 2, 3, 4, 5, 6, 7, 8, 9],表示归并排序已经正确地将原序列排序。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。