Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

can you do it as a function file named weirdSort Given a list of integers, sort

ID: 2249897 • Letter: C

Question

can you do it as a function file named weirdSort

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 [2 46 81357]. 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: 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 file.

Explanation / Answer

Main 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]) : ');
sortedoutput=wierdSort(x);

disp('The sorted numbers are: ')
disp(sortedoutput)
------------------------------------------------------------------------------------   
%function code:

function sortedoutput=wierdSort(x)
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
%**********EVEN SORTING************
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
%***********ODD SORTING************
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
sortedoutput=[xe xo];

Output:

The sorted numbers are:
2 4 8 12 14 16 18 22 1 5 7 9 11 15 19 21

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote