Sort an array of strings based on the given order

28 Feb, 2022
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” Output: “hello”, “geeksforgeeks” Explanation: According to the given order ‘h’ occurs before ‘g’ and hence the words are considered to be sorted.
Input: words = {“word”, “world”, “row”}, order = “worldabcefghijkmnpqstuvxyz” Output: “world”, “word”, “row” Explanation: According to the given order ‘l’ occurs before ‘d’ hence the words “world” will be kept first.  
Approach: To solve the problem mentioned above we need to maintain the priority of each character in the given order. For doing that use Map Data Structure.  
Iterate in the given order and set the priority of a character to its index value.
Use a custom comparator function to sort the array.
In the comparator function, iterate through the minimum sized word between the two words and try to find the first different character, the word with the lesser priority value character will be the smaller word.
If the words have the same prefix, then the word with a smaller size is the smaller word.
Below is the implementation of above approach: 
C++
Python3
Javascript
// C++ program to sort an array// of strings based on the given order #include <bits/stdc++.h>using namespace std; // For storing priority of each characterunordered_map<char, int> mp; // Custom comparator function for sortbool comp(string& a, string& b){     // Loop through the minimum size    // between two words    for (int i = 0;         i < min(a.size(), b.size());         i++) {         // Check if the characters        // at position i are different,        // then the word containing lower        // valued character is smaller        if (mp[a[i]] != mp[b[i]])            return mp[a[i]] < mp[b[i]];    }     /* When loop breaks without returning, it       means the prefix of both words were same       till the execution of the loop.       Now, the word with the smaller size will       occur before in sorted order        */    return (a.size() < b.size());} // Function to print the// new sorted array of stringsvoid printSorted(vector<string> words,                 string order){     // Mapping each character    // to its occurrence position    for (int i = 0; i < order.size(); i++)        mp[order[i]] = i;     // Sorting with custom sort function    sort(words.begin(), words.end(), comp);     // Printing the sorted order of words    for (auto x : words)        cout << x << " ";} // Driver codeint main(){     vector<string> words        = { "word", "world", "row" };    string order        = { "worldabcefghijkmnpqstuvxyz" };     printSorted(words, order);     return 0;}
# Python3 program to sort an array# of strings based on the given orderfrom functools import cmp_to_key # For storing priority of each charactermp = {} # Custom comparator function for sortdef comp(a, b):         # Loop through the minimum size    # between two words    for i in range( min(len(a), len(b))):                 # Check if the characters        # at position i are different,        # then the word containing lower        # valued character is smaller        if (mp[a[i]] != mp[b[i]]):            if mp[a[i]] < mp[b[i]]:                return -1            else:                return 1         '''When loop breaks without returning, it    means the prefix of both words were same    till the execution of the loop.    Now, the word with the smaller size will    occur before in sorted order'''    if (len(a) < len(b)):        return -1    else:        return 1 # Function to print the# new sorted array of stringsdef printSorted(words, order):         # Mapping each character    # to its occurrence position    for i in range(len(order)):        mp[order[i]] = i         # Sorting with custom sort function    words = sorted(words, key = cmp_to_key(comp))         # Printing the sorted order of words    for x in words:        print(x, end = " ") # Driver codewords = [ "word", "world", "row" ]order = "worldabcefghijkmnpqstuvxyz" printSorted(words, order) # This code is contributed by Shivani
<script> // JavaScript program to sort an array// of strings based on the given order // For storing priority of each characterlet mp = new Map(); // Custom comparator function for sortfunction comp(a, b){     // Loop through the minimum size    // between two words    for (let i = 0; i < Math.min(a.length, b.length);i++) {         // Check if the characters        // at position i are different,        // then the word containing lower        // valued character is smaller        if (mp.get(a[i]) != mp.get(b[i]))            return mp.get(b[i]) - mp.get(a[i]);    }     /* When loop breaks without returning, it    means the prefix of both words were same    till the execution of the loop.    Now, the word with the smaller size will    occur before in sorted order        */    return (b.length - a.length);} // Function to print the// new sorted array of stringsfunction printSorted(words,order){     // Mapping each character    // to its occurrence position    for (let i = 0; i < order.length; i++)        mp.set(order[i],i);     // Sorting with custom sort function    words.sort(comp);     // Printing the sorted order of words    for (let x of words)        document.write(x +" ");} // Driver codelet words = ["word", "world", "row" ];let order = ["worldabcefghijkmnpqstuvxyz" ]; printSorted(words, order); // This code is contributed by shinjanpatra </script>
world word row
 
saurabh1990aror
shivanisinghss2110
shinjanpatra
Arrays
Sorting
Strings
Arrays
Strings
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.