Write a version of the bubble sort algorithm in a function called bubbleSort that can be used to sort a string vector object. Also, write a program to test your algorithm. The program should prompt the user for a series of names. The string zzz should end the input stream. Output the sorted list to the console.
*need answer in C++*
Below is the c++ solution with output screenshot
Code :
// including libraries
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
// bubbleSort function to sort the string vector object
vector<string> bubbleSort(vector<string> arr)
{
string temp;
for (int j=0; j<arr.size(); j++)
{
for (int i=j+1; i<arr.size(); i++)
{
if (strcmp(arr[j].c_str(), arr[i].c_str()) > 0)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
// main function
int main()
{
vector<string> names;
string name;
// taking series of names input until user enters zzz
cout<<"Enter series of names (zzz to stop):\n";
while(1){
cin>>name;
if(name == "zzz"){
break;
}
names.push_back(name);
}
names = bubbleSort(names);
// print the sorted names array
cout<<"\nNames after sorting are :\n";
for(int i=0;i<names.size();i++){
cout<<names[i]<<endl;
}
return 0;
}
Output :
Note : for better understanding please refer to the code screenshot below
Get Answers For Free
Most questions answered within 1 hours.