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 CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by