Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Sorting
  • MCQs on Sorting
  • Tutorial on Sorting
  • Bubble Sort
  • Quick Sort
  • Merge Sort
  • Insertion Sort
  • Selection Sort
  • Heap Sort
  • Sorting Complexities
  • Radix Sort
  • ShellSort
  • Counting Sort
  • Bucket Sort
  • TimSort
  • Bitonic Sort
  • Uses of Sorting Algorithm
Open In App
Next Article:
Bubble Sort Algorithm
Next article icon

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

Last Updated : 10 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of strings arr[], the task is to print the strings in lexicographically sorted order. The sorting must be done such that no string is physically copied to another string during the sorting process.

Examples:

Input: arr[] = [“geeks”, “for”, “geeks”, “quiz”]
Output: for geeks geeks quiz

Input: arr[] = [“ball”, “pen”, “apple”, “kite”]
Output: apple ball kite pen

Input: arr[] = [“dog”, “ant”, “zebra”, “bee”]
Output: ant bee dog zebra

Approach:

The idea is to avoid copying actual strings during sorting by using an index array that represents the positions of the original strings. Instead of swapping strings, we compare their values via indices and sort these indices based on the string comparisons. In the end, the strings are printed using the sorted indices, preserving the original array.

–> 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.

Steps to implement the above idea:

  • Initialize an index array of same size as the input vector to store original positions of the strings.
  • Fill this index array with values from 0 to n-1, representing original positions of each string.
  • Use a nested loop to perform selection sort by comparing strings using their index references.
  • In each iteration, find the index that points to the lexicographically smallest string in the unsorted portion.
  • Swap only the indices in the index array, not the actual strings in the original array.
  • After sorting, loop through the sorted index array and print the corresponding strings from the original array.
C++
// C++ program to sort a vector of strings  // without copying actual strings #include <iostream> #include <vector> using namespace std;  // Function to print strings in lexicographical order void sortStrings(vector<string> &arr) {      int n = arr.size();          vector<int> index(n);      // Initialize array to store original indices      // of strings     for (int i = 0; i < n; i++) {         index[i] = i;     }      // Sort based on string comparison     for (int i = 0; i < n - 1; i++) {                  // Assume current index as minimum         int minIdx = i;          // Find index with lexicographically         // smaller string         for (int j = i + 1; j < n; j++) {             if (arr[index[j]] < arr[index[minIdx]]) {                 minIdx = j;             }         }          // Swap indices only         if (minIdx != i) {             swap(index[i], index[minIdx]);         }     }      // Print strings using sorted indices     for (int i = 0; i < n; i++) {         cout << arr[index[i]] << " ";     } }  // Driver code int main() {      vector<string> arr = {"geeks", "for", "geeks", "quiz"};      sortStrings(arr);      return 0; } 
Java
// Java program to sort an array of strings  // without copying actual strings class GfG {      // Function to print strings in lexicographical order     static void sortStrings(String[] arr) {          int n = arr.length;          int[] index = new int[n];          // Initialize array to store original indices          // of strings         for (int i = 0; i < n; i++) {             index[i] = i;         }          // Sort based on string comparison         for (int i = 0; i < n - 1; i++) {              // Assume current index as minimum             int minIdx = i;              // Find index with lexicographically             // smaller string             for (int j = i + 1; j < n; j++) {                 if (arr[index[j]].compareTo(arr[index[minIdx]]) < 0) {                     minIdx = j;                 }             }              // Swap indices only             if (minIdx != i) {                 int temp = index[i];                 index[i] = index[minIdx];                 index[minIdx] = temp;             }         }          // Print strings using sorted indices         for (int i = 0; i < n; i++) {             System.out.print(arr[index[i]] + " ");         }     }      // Driver code     public static void main(String[] args) {          String[] arr = {"geeks", "for", "geeks", "quiz"};          sortStrings(arr);     } } 
Python
# Python program to sort an array of strings  # without copying actual strings  def sortStrings(arr):      n = len(arr)      index = [0] * n      # Initialize array to store original indices      # of strings     for i in range(n):         index[i] = i      # Sort based on string comparison     for i in range(n - 1):          # Assume current index as minimum         minIdx = i          # Find index with lexicographically         # smaller string         for j in range(i + 1, n):             if arr[index[j]] < arr[index[minIdx]]:                 minIdx = j          # Swap indices only         if minIdx != i:             index[i], index[minIdx] = index[minIdx], index[i]      # Print strings using sorted indices     for i in range(n):         print(arr[index[i]], end=" ")  # Driver code if __name__ == "__main__":      arr = ["geeks", "for", "geeks", "quiz"]      sortStrings(arr) 
C#
// C# program to sort an array of strings  // without copying actual strings using System;  class GfG {      // Function to print strings in lexicographical order     public static void sortStrings(string[] arr) {          int n = arr.Length;          int[] index = new int[n];          // Initialize array to store original indices          // of strings         for (int i = 0; i < n; i++) {             index[i] = i;         }          // Sort based on string comparison         for (int i = 0; i < n - 1; i++) {              // Assume current index as minimum             int minIdx = i;              // Find index with lexicographically             // smaller string             for (int j = i + 1; j < n; j++) {                 if (String.Compare(arr[index[j]], arr[index[minIdx]]) < 0) {                     minIdx = j;                 }             }              // Swap indices only             if (minIdx != i) {                 int temp = index[i];                 index[i] = index[minIdx];                 index[minIdx] = temp;             }         }          // Print strings using sorted indices         for (int i = 0; i < n; i++) {             Console.Write(arr[index[i]] + " ");         }     }      // Driver code     public static void Main() {          string[] arr = {"geeks", "for", "geeks", "quiz"};          sortStrings(arr);     } } 
JavaScript
// JavaScript program to sort an array of strings  // without copying actual strings  function sortStrings(arr) {      let n = arr.length;      let index = new Array(n);      // Initialize array to store original indices      // of strings     for (let i = 0; i < n; i++) {         index[i] = i;     }      // Sort based on string comparison     for (let i = 0; i < n - 1; i++) {          // Assume current index as minimum         let minIdx = i;          // Find index with lexicographically         // smaller string         for (let j = i + 1; j < n; j++) {             if (arr[index[j]] < arr[index[minIdx]]) {                 minIdx = j;             }         }          // Swap indices only         if (minIdx !== i) {             let temp = index[i];             index[i] = index[minIdx];             index[minIdx] = temp;         }     }      // Print strings using sorted indices     for (let i = 0; i < n; i++) {         process.stdout.write(arr[index[i]] + " ");     } }  // Driver code let arr = ["geeks", "for", "geeks", "quiz"];  sortStrings(arr); 

Output
for geeks geeks quiz 

Time Complexity: O(n²), due to nested loops during sorting.
Space Complexity: O(n), extra space for index array.

Application in Real World

This approach is useful in scenarios where minimizing disk writes is important, such as sorting an array of structures. Instead of swapping the entire structures, which can be costly in terms of memory and I/O, we compare their values and maintain a separate index array. Sorting is performed by rearranging these indices, effectively representing the sorted order without altering the original data.



Next Article
Bubble Sort Algorithm
author
kartik
Improve
Article Tags :
  • DSA
  • Sorting
  • Strings
Practice Tags :
  • Sorting
  • Strings

Similar Reads

  • Sorting Algorithms
    A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
    3 min read
  • Introduction to Sorting Techniques – Data Structure and Algorithm Tutorials
    Sorting refers to rearrangement of a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. Why Sorting Algorithms are ImportantThe sorting algorithm is important in Com
    3 min read
  • Most Common Sorting Algorithms

    • Selection Sort
      Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted. First we find the smallest element a
      8 min read
    • Bubble Sort Algorithm
      Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high. We sort the array using multiple passes. After the fi
      8 min read
    • Insertion Sort Algorithm
      Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
      9 min read
    • Merge Sort - Data Structure and Algorithms Tutorials
      Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. How do
      14 min read
    • Quick Sort
      QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
      13 min read
    • Heap Sort - Data Structures and Algorithms Tutorials
      Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
      14 min read
    • Counting Sort - Data Structures and Algorithms Tutorials
      Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
      9 min read
    geeksforgeeks-footer-logo
    Corporate & Communications Address:
    A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
    Registered Address:
    K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
    GFG App on Play Store GFG App on App Store
    Advertise with us
    • Company
    • About Us
    • Legal
    • Privacy Policy
    • In Media
    • Contact Us
    • Advertise with us
    • GFG Corporate Solution
    • Placement Training Program
    • Languages
    • Python
    • Java
    • C++
    • PHP
    • GoLang
    • SQL
    • R Language
    • Android Tutorial
    • Tutorials Archive
    • DSA
    • Data Structures
    • Algorithms
    • DSA for Beginners
    • Basic DSA Problems
    • DSA Roadmap
    • Top 100 DSA Interview Problems
    • DSA Roadmap by Sandeep Jain
    • All Cheat Sheets
    • Data Science & ML
    • Data Science With Python
    • Data Science For Beginner
    • Machine Learning
    • ML Maths
    • Data Visualisation
    • Pandas
    • NumPy
    • NLP
    • Deep Learning
    • Web Technologies
    • HTML
    • CSS
    • JavaScript
    • TypeScript
    • ReactJS
    • NextJS
    • Bootstrap
    • Web Design
    • Python Tutorial
    • Python Programming Examples
    • Python Projects
    • Python Tkinter
    • Python Web Scraping
    • OpenCV Tutorial
    • Python Interview Question
    • Django
    • Computer Science
    • Operating Systems
    • Computer Network
    • Database Management System
    • Software Engineering
    • Digital Logic Design
    • Engineering Maths
    • Software Development
    • Software Testing
    • DevOps
    • Git
    • Linux
    • AWS
    • Docker
    • Kubernetes
    • Azure
    • GCP
    • DevOps Roadmap
    • System Design
    • High Level Design
    • Low Level Design
    • UML Diagrams
    • Interview Guide
    • Design Patterns
    • OOAD
    • System Design Bootcamp
    • Interview Questions
    • Inteview Preparation
    • Competitive Programming
    • Top DS or Algo for CP
    • Company-Wise Recruitment Process
    • Company-Wise Preparation
    • Aptitude Preparation
    • Puzzles
    • School Subjects
    • Mathematics
    • Physics
    • Chemistry
    • Biology
    • Social Science
    • English Grammar
    • Commerce
    • World GK
    • GeeksforGeeks Videos
    • DSA
    • Python
    • Java
    • C++
    • Web Development
    • Data Science
    • CS Subjects
    @GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
    We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
    Lightbox
    Improvement
    Suggest Changes
    Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
    geeksforgeeks-suggest-icon
    Create Improvement
    Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
    geeksforgeeks-improvement-icon
    Suggest Changes
    min 4 words, max Words Limit:1000

    Thank You!

    Your suggestions are valuable to us.

    What kind of Experience do you want to share?

    Interview Experiences
    Admission Experiences
    Career Journeys
    Work Experiences
    Campus Experiences
    Competitive Exam Experiences