1. It is often useful to sort an array arrl into ascending order, while simultan
ID: 2249226 • Letter: 1
Question
1. It is often useful to sort an array arrl into ascending order, while simultaneously carrying along a second array arr2. In such a sort, each time an element of array arrl is exchanged with another element of arr1, the corresponding elements of array arr2 are also swapped. When the sort is over, the elements of array arr1 are in ascending order, while the elements of array arr2 that were associated with particular elements of array arr1 are still associated with them. For example, suppose we have the following two arrays: Element arrl arr2 2 10 After sorting array arrl while carrying along array arr2, the contents of the two arrays will be 10 Write a function to sort one real array into ascending order while carrying along a second one. Test the function with the following two 9-element arrays b [31,101,36,-17,0,10,-8,-1,-1];Explanation / Answer
Matlab Script for sorting:
a = [1 11 -6 17 -23 0 5 1 -1];
b = [31 101 36 -17 0 10 -8 -1 -1];
%sorting
for i=1:length(a)-1
for j=i+1:length(a)
if a(i)>a(j)
%swapping a elements
temp = a(i);
a(i) = a(j);
a(j) = temp;
%swapping b elements along with a
temp = b(i);
b(i) = b(j);
b(j) = temp;
end
end
end
command window output:
>> a
a =
-23 -6 -1 0 1 1 5 11 17
>> b
b =
0 36 -1 10 -1 31 -8 101 -17
>>
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.