Help with MATLAB selection sort function???

2 ビュー (過去 30 日間)
Big
Big 2011 年 4 月 27 日
回答済み: BhaTTa 2024 年 8 月 8 日
Modify the selection sort function so that it accepts a second optional argument, which may be either ‘up’ or ‘down’. If the argument is ‘up’, sort the data in ascending order. If the argument is ‘down’, sort the data in descending order. If the argument is missing, the default case is to sort the data in ascending order. (Be sure to handle the case of invalid arguments, and be sure to include the proper help information in your function.)
Any help is appreciated, just kinda confused! Thanks!
  2 件のコメント
Matt Fig
Matt Fig 2011 年 4 月 27 日
Show what you have done so far...
Walter Roberson
Walter Roberson 2011 年 4 月 27 日
What portions have you confused?

サインインしてコメントする。

回答 (1 件)

BhaTTa
BhaTTa 2024 年 8 月 8 日
Here's the modified selection sort function in MATLAB, which includes an optional argument for sorting order. The function will sort the data in ascending order by default, but it can also sort in descending order if specified. Additionally, it handles invalid arguments and includes proper help information.
function sortedArray = selection_sort(arr, order)
% SELECTION_SORT Sorts an array using the selection sort algorithm.
%
% sortedArray = SELECTION_SORT(arr) sorts the array in ascending order.
%
% sortedArray = SELECTION_SORT(arr, order) sorts the array in the
% specified order. The order can be 'up' for ascending or 'down' for
% descending. If order is missing, the default is 'up' (ascending).
%
% Input:
% arr - The array to be sorted.
% order - (Optional) The sorting order: 'up' for ascending or 'down'
% for descending. Defaults to 'up'.
%
% Output:
% sortedArray - The sorted array.
%
% Example:
% sortedArray = SELECTION_SORT([64, 25, 12, 22, 11], 'up')
% sortedArray = SELECTION_SORT([64, 25, 12, 22, 11], 'down')
% sortedArray = SELECTION_SORT([64, 25, 12, 22, 11])
if nargin < 2
order = 'up';
end
if ~ismember(order, {'up', 'down'})
error("Invalid sorting order. Use 'up' for ascending or 'down' for descending.");
end
n = length(arr);
for i = 1:n
% Find the minimum or maximum element in the remaining unsorted array
idx = i;
for j = i+1:n
if (strcmp(order, 'up') && arr(j) < arr(idx)) || (strcmp(order, 'down') && arr(j) > arr(idx))
idx = j;
end
end
% Swap the found element with the first element
arr([i, idx]) = arr([idx, i]);
end
sortedArray = arr;
end
% Example usage:
% sortedArray = selection_sort([64, 25, 12, 22, 11], 'up') % Output: [11, 12, 22, 25, 64]
% sortedArray = selection_sort([64, 25, 12, 22, 11], 'down') % Output: [64, 25, 22, 12, 11]
% sortedArray = selection_sort([64, 25, 12, 22, 11]) % Output: [11, 12, 22, 25, 64]

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by