How Can i write a function that takes a structure array and returns this array with bubble sorting

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

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.
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;
This is like my data and i want to use bubble sort to ordering respect to ages.
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?
I can't call the function. I don't know what should i put in argument side. So i think the header section is wrong. when i write "function a=structarray(a)" is also not working.

댓글을 달려면 로그인하십시오.

 채택된 답변

function a=structarray(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;
end
end

댓글 수: 4

Yeah but how can i call the function
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;
sorted_a = structarray(a);
thanks a lot. but now only a(3) and a(4) changed. Then function stopped.
That is because your bubble sort algorithm needs more work.
You only make a single pass through the data. But suppose the least age was in the last entry. Your code would exchange that with the second last entry, but would not then proceed to "bubble" that lowest age from the second last entry all the way back to the first entry.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Maybe this will work:
ages=[structurearray.age];
[a,b]=sort(ages);
newstructurearray=structurearray(b);
The used structure is attached.

댓글 수: 3

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
That just pushes the sorting off into unique() but the assignment requirement is to use bubble sort.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

질문:

2019년 11월 26일

댓글:

2019년 11월 27일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by