Sort the array of strings according to alphabetical order defined by another string
Last Updated :
23 Feb, 2023
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: for geeksforgeeks best is learning place the
Input: str = "avdfghiwyxzjkecbmnopqrstul",
strArr[] = {"rainbow", "consists", "of", "colours"}
Output: consists colours of rainbow
Approach: Traverse every character of str and store the value in a map with character as the key and its index in the array as the value.
Now, this map will act as the new alphabetical order of the characters. Start comparing the string in the strArr[] and instead of comparing the ASCII values of the characters, compare the values mapped to those particular characters in the map i.e. if character c1 appears before character c2 in str then c1 < c2.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;
// Map to store the characters with their order
// in the new alphabetical order
map<char, int> h;
// Function that returns true if x < y
// according to the new alphabetical order
int Compare(string x, string y)
{
int minSize = min(x.length(), y.length());
for (int i = 0; i < minSize; i++)
{
if (h[x[i]] == h[y[i]])
continue;
return h[x[i]] - h[y[i]];
}
return x.length() - y.length();
}
// Driver code
int main()
{
string str = "fguecbdavwyxzhijklmnopqrst";
vector<string> v { "geeksforgeeks", "is", "the", "best", "place", "for", "learning" };
// Store the order for each character
// in the new alphabetical sequence
h.clear();
for (int i = 0; i < str.length(); i++)
h[str[i]] = i;
sort(v.begin(), v.end(), [](string x, string y) { return Compare(x, y) < 0; });
// Print the strings after sorting
for (auto x : v)
cout << x << " ";
return 0;
}
C#
using System;
using System.Collections.Generic;
class Program
{
// Map to store the characters with their order
// in the new alphabetical order
private static Dictionary<char, int> h = new Dictionary<char, int>();
// Function that returns true if x < y
// according to the new alphabetical order
private static int Compare(string x, string y)
{
int minSize = Math.Min(x.Length, y.Length);
for (int i = 0; i < minSize; i++)
{
if (h[x[i]] == h[y[i]])
continue;
return h[x[i]] - h[y[i]];
}
return x.Length - y.Length;
}
// Driver code
static void Main(string[] args)
{
string str = "fguecbdavwyxzhijklmnopqrst";
List<string> v = new List<string> { "geeksforgeeks", "is", "the",
"best", "place", "for", "learning" };
// Store the order for each character
// in the new alphabetical sequence
h.Clear();
for (int i = 0; i < str.Length; i++)
h[str[i]] = i;
v.Sort((x, y) => Compare(x, y));
// Print the strings after sorting
foreach (var x in v)
Console.Write(x + " ");
Console.ReadLine();
}
}
Java
// Java implementation of the approach
import java.util.Arrays;
import java.util.Comparator;
public class GFG
{
private static void sort(String[] strArr, String str)
{
Comparator<String> myComp = new Comparator<String>()
{
@Override
public int compare(String a, String b)
{
for(int i = 0;
i < Math.min(a.length(),
b.length()); i++)
{
if (str.indexOf(a.charAt(i)) ==
str.indexOf(b.charAt(i)))
{
continue;
}
else if(str.indexOf(a.charAt(i)) >
str.indexOf(b.charAt(i)))
{
return 1;
}
else
{
return -1;
}
}
return 0;
}
};
Arrays.sort(strArr, myComp);
}
// Driver Code
public static void main(String[] args)
{
String str = "fguecbdavwyxzhijklmnopqrst";
String[] strArr = {"geeksforgeeks", "is", "the", "best",
"place", "for", "learning"};
sort(strArr, str);
for(int i = 0; i < strArr.length; i++)
{
System.out.print(strArr[i] + " ");
}
}
}
Python3
# Python3 implementation of the approach
# Function to sort and print the array
# according to the new alphabetical order
def sortStringArray(s, a, n):
# Sort the array according to the new alphabetical order
a = sorted(a, key = lambda word: [s.index(c) for c in word])
for i in a:
print(i, end =' ')
# Driver code
s = "fguecbdavwyxzhijklmnopqrst"
a = ["geeksforgeeks", "is", "the", "best", "place", "for", "learning"]
n = len(a)
sortStringArray(s, a, n)
JavaScript
<script>
// JavaScript implementation of the approach
// Map to store the characters with their order
// in the new alphabetical order
let h = new Map();
// Function that returns true if x < y
// according to the new alphabetical order
function compare(x, y)
{
for (let i = 0; i < Math.min(x.length, y.length); i++) {
if (h.get(x[i]) == h.get(y[i]))
continue;
return h.get(x[i]) - h.get(y[i]);
}
return x.length - y.length;
}
// Driver code
let str = "fguecbdavwyxzhijklmnopqrst";
let v = [ "geeksforgeeks", "is", "the","best", "place", "for", "learning" ];
// Store the order for each character
// in the new alphabetical sequence
h.clear();
for (let i = 0; i < str.length; i++)
h.set(str[i],i);
v.sort(compare);
// Print the strings after sorting
for (let x of v)
document.write(x + " ");
// This code is contributed by shinjanpatra
</script>
Outputfor geeksforgeeks best is learning place the
Complexity Analysis:
- Time Complexity: O(N * log(N)), where N is the size of the string str
- Auxiliary Space: O(N)
Similar Reads
Sort an array of strings based on the given order | Set-2 Given an array of strings words[] and the sequential order of alphabets, the task is to sort the array according to the given order. Assume that the dictionary and the words only contain lowercase English alphabets. Examples: Input: words[] = {âhelloâ, âgeeksforgeeksâ}, order[] = âhlabcdefgijkmnopqr
8 min read
Sort an array of strings based on the given order Given an array of strings words[] and the sequential order of alphabets, our task is to sort the array according to the order given. Assume that the dictionary and the words only contain lowercase alphabets. Examples: Input: words = {"hello", "geeksforgeeks"}, order = "hlabcdefgijkmnopqrstuvwxyz" Ou
7 min read
How to Sort an Array of Strings Using Pointers in C++? In C++, sorting an array of strings using pointers is quite different from normal sorting because here the manipulation of pointers is done directly, and then according to which string is pointed by the pointer the sorting is done. The task is to sort a given array of strings using pointers. Example
2 min read
Sort an array of string of dates in ascending order Given an array of strings dates[], the task is to sort these dates in ascending order. Note: Each date is of the form dd mmm yyyy where: Domain of dd is [0-31].Domain of mmm is [Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec].And, yyyy is a four digit integer. Examples: Input: dates[] =
7 min read
C Program to Sort a String of Characters Sorting a string of characters refers to the process of rearranging all the characters in the given order. In this article, we will learn how to sort a string of characters using the C program.The most straightforward method to sort a string of characters is by using the qsort() function. Let's take
3 min read