Once the pets are all entered, they want to be able to sort the list by any of t
ID: 3672449 • Letter: O
Question
Once the pets are all entered, they want to be able to sort the list by any of the four columns.
It should ask the user how many pets they want to enter, and then it should provide a means to enter the four pieces of data about each pet.
Once that is done, the program should present a menu allowing the user to choose how to sort the list. (A simple bubble sort is fine for this.)
It should then display the information in tabular format sorted as requested.
Finally, the program should ask if the user would like to sort again, allow the user to continue sorting on different columns and displaying the output until they indicate they are done.
Explanation / Answer
C++ code:
#include <bits/stdc++.h>
using namespace std;
void swap(string ** arr,int i,int j){
string temp;
temp=arr[i][0];
arr[i][0]=arr[j][0];
arr[j][0]=temp;
temp=arr[i][1];
arr[i][1]=arr[j][1];
arr[j][1]=temp;
temp=arr[i][2];
arr[i][2]=arr[j][2];
arr[j][2]=temp;
temp=arr[i][3];
arr[i][3]=arr[j][3];
arr[j][3]=temp;
}
void sortarr(string** arr,int n,int x){
for (int c = 0 ; c < ( n - 1 ); c++){
for (int d = 0 ; d < n - c - 1; d++){
if (string(arr[d][x])>string(arr[d+1][x])){
swap(arr,d+1,d);
}
}
}
}
void display(string ** arr,int n){
for(int i=0;i<n;i++){
cout<<setw(10) << left <<arr[i][0]<<setw(10) << left <<arr[i][1]<<setw(20) << left <<arr[i][2]<<setw(20) << left <<arr[i][3]<<endl;
}
}
int main(){
int n;
string s;
cout<<"Welcome to the Pet Adoptation Center!"<<endl<<endl;
cout<<"How many pets do you want to put for adoptation? ";
cin>>n;
getline(cin,s);
string **arr=new string*[n];
for(int i=0;i<n;i++){
string *ar=new string[4];
cout<<"Pet #"<<i+1<<endl;
cout<<"name: ";
getline(cin,s);
ar[0]=s;
cout<<"species: ";
getline(cin,s);
ar[1]=s;
cout<<"breed: ";
getline(cin,s);
ar[2]=s;
cout<<"gender: ";
getline(cin,s);
ar[3]=s;
arr[i]=ar;
}
s="y";
int x;
while(s=="y"){
cout<<"Sort by:"<<endl;
cout<<"1 - name"<<endl;
cout<<"2 - species"<<endl;
cout<<"3 - breed"<<endl;
cout<<"4 - gender"<<endl;
cin>>x;
sortarr(arr,n,x-1);
display(arr,n);
cout<<"Sort again? (y/n): ";
cin>>s;
cout<<s;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.