In: Computer Science
Write a version of the selection sort algorithm in a function called selectionSort 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++*
#include <iostream>
#include <vector>
template<typename T>
void selection_sort(std::vector<T>& array)
{
typedef typename std::vector<T>::iterator
Itr;
Itr itr = array.begin();
while(itr != array.end())
{
Itr itr_min = itr;
for(Itr i = itr + 1; i
!= array.end(); i++)
{
if(*i < *itr_min)
{
itr_min = i;
}
}
std::iter_swap(itr,
itr_min);
itr++;
}
}
template<typename T>
void print(const std::vector<T>& array)
{
for(auto itr = array.begin(); itr !=
array.end(); itr++)
{
std::cout << *itr
<< " ";
}
std::cout << '\n';
}
int main()
{
std::vector<std::string> str({"code",
"live", "love", "sing", "create"});
std::cout << "Original Array :";
print(str);
selection_sort(str);
std::cout <<"Sorted Array :";
print(str);
std::cout << '\n';
}
Please refer to the screenshot of the code to understand the indentation of the code
Output:
Hope this helped. Please do upvote and if there are any queries please ask in comments section.