Help with MATLAB selection sort function???
Afficher commentaires plus anciens
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 commentaires
Matt Fig
le 27 Avr 2011
Show what you have done so far...
Walter Roberson
le 27 Avr 2011
What portions have you confused?
Réponses (1)
BhaTTa
le 8 Août 2024
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]
Catégories
En savoir plus sur Shifting and Sorting Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!