In: Electrical Engineering
Write a code block to perform nested-for-loop sorting on a vector of State objects, arranging by their string name attribute in alphabetical order A-Z. Assume all names are fully uppercase and that there's an assignment operator for the class. The name of the vector is "states".
Ques:
Ans:
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks
//required nested for loop to sort State objects vector named states.
//assuming name field in State is public.
//using bubble sort algorithm
//looping from i=0 to states.size()-1
for(int i=0;i<states.size();i++){
//looping from j=0 to states.size()-i-2
for(int j=0;j<states.size()-i-1;j++){
//comparing names of states at j and j+1
if(states[j].name > states[j+1].name){
//swapping states at j and j+1
State temp=states[j];
states[j]=states[j+1];
states[j+1]=temp;
}
}
}