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

void sort(book_info bo[], int k) { string temp, temp1, temp2, temp3, temp4, temp

ID: 3643701 • Letter: V

Question

void sort(book_info bo[], int k)
{
string temp, temp1, temp2, temp3, temp4, temp7;
int temp5, temp6, temp8;
bool swap;

do{swap=false;
for(int pos=0; pos<k-1; pos++)
if(bo[pos].title>bo[pos+1].title){
temp=bo[pos].title;
temp1=bo[pos].author.firstname;
temp2=bo[pos].author.lastname;
temp3=bo[pos].genre;
temp4=bo[pos].publisher.pubname;
temp5=bo[pos].publisher.year;
temp6=bo[pos].publisher.num_pages;
temp7=bo[pos].format;
temp8=bo[pos].stars;

bo[pos].title=bo[pos+1].title;
bo[pos].author.firstname=bo[pos+1].author.firstname;
bo[pos].author.lastname=bo[pos+1].author.lastname;
bo[pos].genre=bo[pos+1].genre;
bo[pos].publisher.pubname=bo[pos+1].publisher.pubname;
bo[pos].publisher.year=bo[pos+1].publisher.year;
bo[pos].publisher.num_pages=bo[pos+1].publisher.num_pages;
bo[pos].format=bo[pos+1].format;
bo[pos].stars=bo[pos+1].stars;

bo[pos+1].title=temp;
bo[pos+1].author.firstname=temp1;
bo[pos+1].author.lastname=temp2;
bo[pos+1].genre=temp3;
bo[pos+1].publisher.pubname=temp4;
bo[pos+1].publisher.year=temp5;
bo[pos+1].publisher.num_pages=temp6;
bo[pos+1].format=temp7;
bo[pos+1].stars=temp8;

swap=true;
}

}while(swap);

return;
}

how to make this function more compact? what is object assignment??? Help me please!

Explanation / Answer

Write a swap_item function: template void swap_item(T & first, T & second) { T temp = first; first = second; second = temp; } Put this above you function. Then change you function to: void sort(book_info bo[], int k) { bool swap; do { swap=false; for(int pos=0; posbo[pos+1].title) { swap_item(bo[pos].title, bo[pos+1].title); swap_item(bo[pos].author.firstname, bo[pos+1].author.firstname); swap_item(bo[pos].author.lastname, bo[pos+1].author.lastname); swap_item(bo[pos].genre, bo[pos+1].genre); swap_item(bo[pos].publisher.pubname, bo[pos+1].publisher.pubname); swap_item(bo[pos].publisher.year, bo[pos+1].publisher.year); swap_item(bo[pos].publisher.num_pages, bo[pos+1].publisher.num_pages); swap_item(bo[pos].format, bo[pos+1].format); swap_item(bo[pos].stars, bo[pos+1].stars); swap=true; } }while(swap); return; }