# Print array of strings in sorted order without copying one string into another in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

In the problem to print an array of strings in sorted order without copying one string into another, we need to sort the array of string. Here the programmer cannot copy a string into another string while sorting.

Let’s take an example to understand the concept better :

Example

Input : {“Delhi”, “Hyderabad”, “Indore”, “Mumbai”, “Banglore”}
Output : Banglore, Delhi, Hyderabad, Indore, Mumbai

Explanation − Lexicographically the ordering is done. So, Bangalore starting with B comes first and Mumbai starting with M comes last.

Now, let's try to derive a solution to our problem.

To solve the problem, we can create an array that stores the correct index of these string because actually changing positions of the string needs coping to be done. So this is one possible way to solve the problem.

We will use an index array and use the sorting technique to sort it and then print it. Here, we will use a selection sort technique that uses direct comparisons.

## Example

Now let's create a program to illustrate the working −

Live Demo

#include <iostream>
using namespace std;
void sortedStringArray(string arr[], int n){
int stringIndex[n];
int i, j, min;
for (i=0; i<n; i++)
stringIndex[i] = i;
for (i=0; i<n-1; i++){
min = i;
for (j=i+1; j<n; j++){
if (arr[stringIndex[min]].compare(arr[stringIndex[j]]) > 0)
min = j;
}
if (min != i){
int temp = stringIndex[min];
stringIndex[min] = stringIndex[i];
stringIndex[i] = temp;
}
}
for (i=0; i<n; i++)
cout << arr[stringIndex[i]] << ", ";
}
int main(){
string arr[] = {"Delhi", "Hyderabad", "Indore", "Mumbai", "Banglore"};
int n = 5;
sortedStringArray(arr, n);
return 0;
}

## Output

Banglore, Delhi, Hyderabad, Indore, Mumbai,
Updated on 03-Jan-2020 09:42:54