How can I count the number of swaps that occur when sorting a vector?

2 views (last 30 days)
I am trying to reveal the number of swaps that occur when I sort a vector as ascending and descending. What would I need to code to allow the program to display the number of times the numbers swapped to get the final vector.
Current code for reference:
function out = sum2(varargin)
% Function accepts variable number of inputs and sorts them into an array.
% This function includes help text, ascending and descending orders, number
% of swaps, and an issued error.
% a = input
% b = input in ascending order
% k = input in descending order
%
% See also VARARGIN, NARGIN, SORT, HELP, ERROR.
fprintf('Total number of inputs = %d\n',nargin);
nVarargs = length(varargin);
fprintf('Inputs in varargin(%d)\n',nVarargs)
for i = 1:nargin
a = cell2mat(varargin);
c = mat2str(a);
b = sort(c,'ascend');
k = sort(c,'descend');
end
input = c
ascending = b
descending = k
  2 Comments
Stephen23
Stephen23 on 24 Apr 2017
Edited: Stephen23 on 24 Apr 2017
It might be possible to modify the Wagner-Fischer algorithm (for calculating the Levenshtein distance, or edit distance) to only count swaps of position:
Possibly the only "robust" way to count the number of swaps is to implement your own sorting algorithm.

Sign in to comment.

Accepted Answer

Rik
Rik on 24 Apr 2017
If you mean how many steps the algorithm has taken, that is impossible and might change between Matlab releases. If you want to know the number of differing positions you can try some code like this:
[a_sorted,index_a]=sort(a);
swaps_a=sum(index_a~=(1:length(a)));
PS don't overwrite the function input with a variable, it is super useful.

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!