Introduction:
Write a version of the selection sort algorithm that can be used to sort a list
of strings.
Source: MindTap Computing for Malik's C++ Programming From Problem Analysis to Program Design, 8th Edition, [Instant Access] (8th)-Malik, chapter 16, programming exercises 8.
Solved!
The
objective of the programming exercise is to write a function to sort a given
list of strings using selection sort.
Program Plan:
· Define
header section.
· Define void selectionSort(vector<string>
&arr) function
that take vector of string as pass by reference.
o
Declare array size int n =
arr.size().
o
Use for loop i from 0 to n-2.
§ Declare
int
min_index = i, tracks minimum element index in array arr[i]...arr[n-1].
§ Use for
loop j from i+1
to
n-1.
· If arr[j]
< arr[min_index].
o
Assignment j to min_index.
§ Swap
element at index i and min_index.
· Define main() function
(testing function).
o
Declare int n variable.
o
Take user input for list size n.
o
Declare vector<string> arr(n).
o
Take user input for strings using for
loop.
o
Call to function
selectionSort().
o
Print the list of the string after sorting
using for loop.
Program:
// write a function to sort a given list of strings using selection sort.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// selectionSort() that take vector of string as reference parameter.
// and sort given list using selection sort algorithm.
void selectionSort(vector<string> &arr)
{
int n = arr.size();
// for loop i from 0 to n-2.
for (int i = 0; i < n - 1; i++)
{
// set min_index to i.
// min_index tracks minimum element index in array arr[i]...arr[n-1].
int min_index = i;
for (int j = i + 1; j < n; j++)
{
// if arr[j] is less than arr[min_index] .
if (arr[j] < arr[min_index])
{
// assignment j to min_index.
min_index = j;
}
}
// swap element at index i and min_index
swap(arr[i], arr[min_index]);
}
}
// driver program.
int main()
{
// declare variable n.
int n;
cout << "Enter size of list of string: ";
// take user input.
cin >> n;
// declare vector arr of string of size n.
vector<string> arr(n);
// take user input for arr vector using for loop.
cout << "Enter " << n << " words: " << endl;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
cout << endl;
// call to selection sort function.
selectionSort(arr);
// print array after sortting.
cout << "List of string after selection sort: ";
for (int i = 0; i < n; i++)
{
cout << arr[i] << ", ";
}
cout << endl;
// end.
return 0;
}
Output:
0 Comments
If you have any doubt let me know.