183k views
4 votes
Given an array of strings of length n, write a C++ program to

sort these strings
in alphabetical order. You have to use INSERTION-SORT
algorithm.

1 Answer

4 votes

Final answer:

To alphabetically sort an array of strings in C++, we can implement the insertion sort algorithm, which involves inserting each array element into its proper position within a sorted subset.

Step-by-step explanation:

Implementing Insertion Sort to Alphabetically Order Strings in C++

To sort an array of strings using the insertion sort algorithm, compare string elements and arrange them in alphabetical order by repeatedly inserting a particular element into its correct position within a sorted subset of the array.

The following C++ code demonstrates this process:

#include
#include
#include

using namespace std;

void InsertionSort(vector& arr) {
for (int i = 1; i < arr.size(); i++) {
string key = arr[i];
int j = i - 1;

// Compare and insert key into its correct position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}

int main() {
vector strings = {"banana", "apple", "cherry"};
InsertionSort(strings);

// Output the sorted array
for (const string& str : strings) {
cout << str << '\\';
}

return 0;
}

In the provided program, we define an InsertionSort function that takes a reference to a vector of strings. Inside this function, we iterate over the array elements and insert each element into its appropriate place in the already sorted section of the array. This way, by the end of the function, we will have a list of strings sorted in alphabetical order.

User Shivam Mathur
by
7.7k points