Open In App

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

Last Updated : 12 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of n strings. The task is to print the strings in sorted order. The approach should be such that no string should be copied to another string during the sorting process.

Examples:

Input : {"geeks", "for", "geeks", "quiz")
Output : for geeks geeks quiz

Input : {"ball", "pen", "apple", "kite"}
Output : apple ball kite pen

Approach: It has the following steps: 

  1. Maintain another array indexed_arr which stores/maintain the index of each string.
  2. We can apply any sorting technique to this indexed_arr.

An Illustration:  

--> str[] = {"world", "hello"}
--> corresponding index array will be
    indexed_arr = {0, 1}
--> Now, how the strings are compared and 
    accordingly values in indexed_arr are changed.
--> Comparison process:
    if (str[index[0]].compare(str[index[1]] > 0
        temp = index[0]
        index[0] = index[1]
        index[1] = temp

// after sorting values of
// indexed_arr = {1, 0}
--> for i=0 to 1
        print str[index[i]]

This is how the strings are compared and their 
corresponding indexes in the indexed_arr
are being manipulated/swapped so that after the sorting process
is completed, the order of indexes in the indexed_arr
gives us the sorted order of the strings.

Implementation:

C++




// C++ implementation to print array of strings in sorted
// order without copying one string into another
#include <bits/stdc++.h>
 
using namespace std;
 
// function to print strings in sorted order
void printInSortedOrder(string arr[], int n)
{
    int index[n];
    int i, j, min;
     
    // Initially the index of the strings
    // are assigned to the 'index[]'
    for (i=0; i<n; i++)
        index[i] = i;
     
    // selection sort technique is applied   
    for (i=0; i<n-1; i++)   
    {
        min = i;
        for (j=i+1; j<n; j++)
        {
            // with the help of 'index[]'
            // strings are being compared
            if (arr[index[min]].compare(arr[index[j]]) > 0)
                min = j;
        }
         
        // index of the smallest string is placed
        // at the ith index of 'index[]'
        if (min != i)
        {
            int temp = index[min];
            index[min] = index[i];
            index[i] = temp;
        }
    }
     
    // printing strings in sorted order
    for (i=0; i<n; i++)
        cout << arr[index[i]] << " ";
}
 
// Driver program to test above
int main()
{
    string arr[] = {"geeks", "quiz", "geeks", "for"};
    int n = 4;
    printInSortedOrder(arr, n);
    return 0;
}


Java




//Java implementation to print array of strings in sorted
// order without copying one string into another
 
class GFG {
 
    // function to print strings in sorted order
    static void printInSortedOrder(String arr[], int n) {
        int index[] = new int[n];
        int i, j, min;
 
        // Initially the index of the strings
        // are assigned to the 'index[]'
        for (i = 0; i < n; i++) {
            index[i] = i;
        }
 
        // selection sort technique is applied   
        for (i = 0; i < n - 1; i++) {
            min = i;
            for (j = i + 1; j < n; j++) {
                // with the help of 'index[]'
                // strings are being compared
                if (arr[index[min]].compareTo(arr[index[j]]) > 0) {
                    min = j;
                }
            }
 
            // index of the smallest string is placed
            // at the ith index of 'index[]'
            if (min != i) {
                int temp = index[min];
                index[min] = index[i];
                index[i] = temp;
            }
        }
 
        // printing strings in sorted order
        for (i = 0; i < n; i++) {
            System.out.print(arr[index[i]] + " ");
        }
    }
 
    // Driver program to test above
    static public void main(String[] args) {
        String arr[] = {"geeks", "quiz", "geeks", "for"};
        int n = 4;
        printInSortedOrder(arr, n);
    }
}
 
// This code is contributed by 29AjayKumar


Python 3




# Python 3 implementation to print array
# of strings in sorted order without
# copying one string into another
 
# function to print strings in sorted order
def printInSortedOrder(arr, n):
    index = [0] * n
     
    # Initially the index of the strings
    # are assigned to the 'index[]'
    for i in range(n):
        index[i] = i
     
    # selection sort technique is applied
    for i in range(n - 1):
        min = i
        for j in range(i + 1, n):
             
            # with the help of 'index[]'
            # strings are being compared
            if (arr[index[min]] > arr[index[j]]):
                min = j
         
        # index of the smallest string is placed
        # at the ith index of 'index[]'
        if (min != i):
            index[min], index[i] = index[i], index[min]
     
    # printing strings in sorted order
    for i in range(n):
        print(arr[index[i]], end = " ")
 
# Driver Code
if __name__ == "__main__":
     
    arr = ["geeks", "quiz", "geeks", "for"]
    n = 4
    printInSortedOrder(arr, n)
 
# This code is contributed by ita_c


C#




     
//C# implementation to print an array of strings in sorted
// order without copying one string into another
 using System;
public class GFG {
  
    // function to print strings in sorted order
    static void printInSortedOrder(String []arr, int n) {
        int []index = new int[n];
        int i, j, min;
  
        // Initially the index of the strings
        // are assigned to the 'index[]'
        for (i = 0; i < n; i++) {
            index[i] = i;
        }
  
        // selection sort technique is applied   
        for (i = 0; i < n - 1; i++) {
            min = i;
            for (j = i + 1; j < n; j++) {
                // with the help of 'index[]'
                // strings are being compared
                if (arr[index[min]].CompareTo(arr[index[j]]) > 0) {
                    min = j;
                }
            }
  
            // index of the smallest string is placed
            // at the ith index of 'index[]'
            if (min != i) {
                int temp = index[min];
                index[min] = index[i];
                index[i] = temp;
            }
        }
  
        // printing strings in sorted order
        for (i = 0; i < n; i++) {
            Console.Write(arr[index[i]] + " ");
        }
    }
  
    // Driver program to test above
    static public void Main() {
        String []arr = {"geeks", "quiz", "geeks", "for"};
        int n = 4;
        printInSortedOrder(arr, n);
    }
}
  
// This code is contributed by 29AjayKumar


Javascript




<script>
//Javascript implementation to print array of strings in sorted
// order without copying one string into another
     
    // function to print strings in sorted order
    function printInSortedOrder(arr,n)
    {
        let index = new Array(n);
        let i, j, min;
   
        // Initially the index of the strings
        // are assigned to the 'index[]'
        for (i = 0; i < n; i++) {
            index[i] = i;
        }
   
        // selection sort technique is applied   
        for (i = 0; i < n - 1; i++) {
            min = i;
            for (j = i + 1; j < n; j++) {
                // with the help of 'index[]'
                // strings are being compared
                if (arr[index[min]]>(arr[index[j]]) ) {
                    min = j;
                }
            }
   
            // index of the smallest string is placed
            // at the ith index of 'index[]'
            if (min != i) {
                let temp = index[min];
                index[min] = index[i];
                index[i] = temp;
            }
        }
   
        // printing strings in sorted order
        for (i = 0; i < n; i++) {
            document.write(arr[index[i]] + " ");
        }
    }
     
    // Driver program to test above
    let arr=["geeks", "quiz", "geeks", "for"];
    let n = 4;
    printInSortedOrder(arr, n);
     
    // This code is contributed by avanitrachhadiya2155
</script>


Output

for geeks geeks quiz 

Time Complexity: O(n2).
Auxiliary Space: O(n).

The approach can have its usage when we have to minimize the number of disc writes as in the case of an array of structures. The structure values are compared, but their values are not being swapped, instead, their index is maintained in another array, which is manipulated to keep the indexes in an order which represents the sorted array of structures.



Similar Reads

Sort an array of strings in ascending order with each string sorted in descending order
Given a array of strings S[] of size N (1 ? N ? 105), sort characters of each string in descending order and then print the array of strings in ascending order. Examples: Input: s[] = {"apple", "box", "cat"} Output: pplea tca xob Explanation: Sorting each string in descending order, S[] modifies to {"pplea", "xob", "tca"}. Sorting the array in asce
9 min read
Print all possible ways to convert one string into another string | Edit-Distance
Prerequisite: Dynamic Programming | Set 5 (Edit Distance) Given two strings str1 and str2, the task is to print the all possible ways to convert ‘str1’ into ‘str2’. Below are the operations that can be performed on "str1": InsertRemoveReplaceAll of the above operations are of equal cost. The task is to print all the various ways to convert 'str1' i
25 min read
Check whether two strings can be made equal by copying their characters with the adjacent ones
Given two strings str1 and str2, the task is to check whether both of the string can be made equal by copying any character of the string with its adjacent character. Note that this operation can be performed any number of times.Examples: Input: str1 = "abc", str2 = "def" Output: No As all the characters in both the string are different. So, there
5 min read
Pre Order, Post Order and In Order traversal of a Binary Tree in one traversal | (Using recursion)
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order in one iteration. Examples: Input: [caption width="800"] [/caption] Output: Pre Order: 1 2 4 5 3 6 7 Post Order: 4 5 2 6 7 3 1 In Order: 4 2 5 1 6 3 7 Input: [caption width="800"] [/caption] Output: Pre Order: 1 2 4 8 12 5 9 3 6 7 10 11
9 min read
Print all elements in sorted order from row and column wise sorted matrix
Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print all elements of the matrix in sorted order. Example: Input: mat[][] = { {10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}, };Output: 10 15 20 25 27 29 30 32 33 35 37 39 40 45 48 50 Recommended PracticeSorted matrixTry It! We can use Young
26 min read
heapq in Python to print all elements in sorted order from row and column wise sorted matrix
Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print all elements of matrix in sorted order. Examples: Input : mat= [[10, 20, 30, 40], [15, 25, 35, 45], [27, 29, 37, 48], [32, 33, 39, 50]] Output : Elements of matrix in sorted order [10, 15, 20, 25, 27, 29, 30, 32, 33, 35, 37, 39, 40, 45, 48, 50] This problem h
2 min read
Sort the array of strings according to alphabetical order defined by another string
Given a string str and an array of strings strArr[], the task is to sort the array according to the alphabetical order defined by str. Note: str and every string in strArr[] consists of only lower case alphabets. Examples: Input: str = "fguecbdavwyxzhijklmnopqrst", strArr[] = {"geeksforgeeks", "is", "the", "best", "place", "for", "learning"} Output
5 min read
Print elements of an array according to the order defined by another array | set 2
Given two arrays a1[] and a2[], print elements of a1 in such a way that the relative order among the elements will be the same as those are in a2. That is, elements which come before in the array a2[], print those elements first from the array a1[]. For the elements not present in a2, print them at last in sorted order. It is also given that the nu
7 min read
Count of strings that become equal to one of the two strings after one removal
Given two strings str1 and str2, the task is to count all the valid strings. An example of a valid string is given below: If str1 = "toy" and str2 = "try". Then S = "tory" is a valid string because when a single character is removed from it i.e. S = "tory" = "try" it becomes equal to str1. This property must also be valid with str2 i.e. S = "tory"
9 min read
Merge two Maps of Array into one sorted Map of Array
Given two maps map1 and map2 having a string as the key and arrays of integers as values, the task is to merge them in one map such that if a key is common in both the maps, the respective arrays should be merged. Examples: Input: map1 = { ("key1", {0, 1}), ("key2", {0, 1}) }, map2 = { ("key2", {1, 2}) };Output: { (key1, {0, 1}), (key2, {0, 1, 2})
12 min read
Article Tags :
Practice Tags :