Given a list of integers, sort it as follows: normal lexicographical sort order
ID: 2249921 • Letter: G
Question
Given a list of integers, sort it as follows: normal lexicographical sort order (i.e. 2 before 3), but any odd number is greater than any even number. For example, if the input is the list 1:8, the answer should be 24681 3 5 7]. Do not use MATLAB's built-in sort(s) function for this. To test your code, you can make up some data. Here is a suggestion: data = [22 7 12 5 2 15 9 19 4 14 8 21 18 11 16 1] Submit either a script which demonstrates your code, or a function file named weirdSort with one argument (vector of unsorted numbers) that returns the sorted vector. In either case, submit one .m fileExplanation / Answer
By given data
input= 1:8
matlab code:
clc
clear all
x=[22 7 12 5 2 15 9 19 4 14 8 21 18 11 16 1];
%x=input('Enter any range of values in matrix form (e.g: [1 2 3]) : ');
a=0;b=0;
for i=1:length(x)
if(mod(x(i),2)==0) % checking for even numbers
a=a+1;
xe(a)=x(i); %even numbers
else
b=b+1;
xo(b)=x(i); %odd numbers
end
end
for j=1:1:length(xe)-1
% comparing each number with the next and swapping
for i=1:1:length(xe)-1
if xe(i)>xe(i+1);
% temp is a variable where the numbers are kept
% temporarily for the switch
temp=xe(i);
xe(i)=xe(i+1);
xe(i+1)=temp;
end
end
end
for j=1:1:length(xo)-1
% comparing each number with the next and swapping
for i=1:1:length(xo)-1
if xo(i)>xo(i+1);
% temp is a variable where the numbers are kept
% temporarily for the switch
temp=xo(i);
xo(i)=xo(i+1);
xo(i+1)=temp;
end
end
end
xsorted=[xe xo];
disp('The sorted numbers are: ')
disp(xsorted)
Output:
the sorted numbers are:
2 4 8 12 14 16 18 22 1 5 7 9 11 15 19 21
2 4
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.