How Can i write a function that takes a structure array and returns this array with bubble sorting
Mostra commenti meno recenti
I want to write a function that takes a structure array holding information about students(name,age,gpa etc.) and returns this array by ordering the students with respect to their age by bubble sort.
function a=structarray (age,a)
for i=1:length(a)-1
if a(i).(age)>a(i+1).(age)
T=a(i);
a(i)=a(i+1);
a(i+1)=T;
i write this. but of course it is not working.pls guys help me.
4 Commenti
Walter Roberson
il 26 Nov 2019
What inputs would be typical for the age parameter ?
By the way:
a([i, i+1]) = a([i+1,i]);
exchanges without needing any temporary variable.
Dart Min
il 26 Nov 2019
Walter Roberson
il 26 Nov 2019
When you call the function, passing in that a as the second parameter, what would you pass in as the first parameter?
What difficulties are you observing with your code?
Dart Min
il 26 Nov 2019
Risposta accettata
Più risposte (1)
Stijn Haenen
il 26 Nov 2019
Maybe this will work:
ages=[structurearray.age];
[a,b]=sort(ages);
newstructurearray=structurearray(b);
The used structure is attached.
3 Commenti
Walter Roberson
il 26 Nov 2019
sort() is not a bubble sort.
Stijn Haenen
il 26 Nov 2019
Ah i missed that,
maybe this:
a(1).name='Matt';
a(1).age=22;
a(1).gpa=77;
a(2).name='Chris';
a(2).age=23;
a(2).gpa=45;
a(3).name='Park';
a(3).age=26;
a(3).gpa=81;
a(4).name='Stewie';
a(4).age=19;
a(4).gpa=44;
ages=[a.age];
[b]=unique(ages);
new_a=[];
for i=1:numel(b)
num=(ages==b(i));
new_a=[new_a;a(num)];
end
Walter Roberson
il 27 Nov 2019
That just pushes the sorting off into unique() but the assignment requirement is to use bubble sort.
Categorie
Scopri di più su Multidimensional Arrays in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!