MATLAB实现搬运的排序 【例】

带有搬运的排序。对数组arr1 进行升序排序,与arr1 中相对应的arr2 中的元素也
要发生改变。对这个种排序,每次arr1 中的一个元素与另一个元素进行交换,arr2 中对应的
元素也要进行相应的交换。当排序结束时arr1 中的元素按升序排列,arr2 中的元素也会有相
应的变化。
当arr1 的数组排序结束后,arr2 也要进行相应的变化。两数组为
编写一个程序,对第一个实数组进行按降序排列,对第二个数组进行相应交化。用下面
两个数组检测你的程序
a = [-1, 11, -6, 17, -23, 0, 5, 1, -1];
b = [-31, 102, 36, -17, 0, 10, -8, -1, -1];


1.ssort00.m

function [out1,out2] = ssort00(a,b)
%SSORT Selection sort data in ascending order
% Function SSORT sorts a numeric data set into
% ascending order. Note that the selection sort
% is relatively inefficient. DO NOT USE THIS
% FUNCTION FOR LARGE DATA SETS. Use MATLAB's
% "sort" function instead.
% Define variables:
% a --Input array to sort
% ii --Index variable
% iptr --Pointer to min value
% jj --Index variable
% nvals --Number of values in "a"
% out --Sorted output array
% temp --Temp variable for swapping
% Record of revisions:
% Date Programmer Description of change
% ==== ========== =====================
% 12/19/98 S. J. Chapman Original code
% Get the length of the array to sort
nvals = size(a,2);
% Sort the input array
for ii = 1:nvals-1
% Find the minimum value in a(ii) through a(n)
iptr = ii;
for jj = ii+1:nvals
if a(jj) < a(iptr)
iptr = jj;
end
end
% iptr now points to the minimum value, so swap a(iptr)
% with a(ii) if ii ~= iptr.
if ii ~= iptr
temp1 = a(ii);
temp2=b(ii);
a(ii) = a(iptr);
b(ii)=b(iptr);
a(iptr) = temp1;
b(iptr)=temp2;
end
end
% Pass data back to caller
out1 = a;
out2 = b;


2.test.m
clc
clear all
nvals = input('Enter number of values to sort: ');
% Preallocate array
array1 = zeros(1,nvals);
array2 = zeros(1,nvals);
% Get input values
for i = 1:nvals
%Prompt for next value
string1 = ['Enter a value ' int2str(i) ': '];
array1(i)=input(string1);
end
for ii = 1:nvals
%Prompt for next value
string2 = ['Enter b value ' int2str(ii) ': '];
array2(ii)=input(string2);
end
% Now sort the data
[out1,out2]=ssort00(array1,array2);
% Display the sorted result.
fprintf('\nBefore sorted data:\n');
for iii = 1:nvals
fprintf('%d  ',array1(iii));
end
fprintf('\n');
for iiii = 1:nvals
fprintf('%d  ',array2(iiii));
end
fprintf('\nAfter sorted data:\n');
for iii = 1:nvals
fprintf('%d  ',out1(iii));
end
fprintf('\n');
for iiii = 1:nvals
fprintf('%d  ',out2(iiii));
end
fprintf('\n');
posted @ 2013-03-12 12:34  dreamsyeah  阅读(309)  评论(0编辑  收藏  举报