[Question]
  [
I recently had a problem to solve at work where I had two lists: a master list, and a smaller list that contains a subset of the items in the master list potentially in a different order. I needed to reorder the master list in such a way that the items in the subset would appear in the same order without changing the order of the items not found in the list and keeping items in the same location whenever possible. Okay, that probably sounds confusing, so I'll break it down:
* The master list defines the default order of items.
* The subset list defines relative order of certain items.
* Where the master list has two elements out of order according to the subset list, the item that is earlier in the master list should be moved to the earliest index where it is in the correct location relative to other items within the subset list. (i.e. immediately after the later item)
Your task is to implement this reordering algorithm.
## Example Test Cases
```
Master: [1, 2, 3]
Subset: []
Result: [1, 2, 3]
```
---
```
Master: [9001, 42, 69, 1337, 420]
Subset: [69]
Result: [9001, 42, 69, 1337, 420]
```
---
```
Master: [9001, 42, 69, 1337, 420, 99, 255]
Subset: [69, 9001, 1337]
Result: [42, 69, 9001, 1337, 420, 99, 255]
```
---
```
Master: [1, 2, 3, 4, 5]
Subset: [2, 5]
Result: [1, 2, 3, 4, 5]
```
---
```
Master: [apple, banana, carrot, duck, elephant]
Subset: [duck, apple]
Result: [banana, carrot, duck, apple, elephant]
```
---
```
Master: [Alice, Betty, Carol, Debbie, Elaine, Felicia, Georgia, Helen, Ilene, Julia]
Subset: [Betty, Felicia, Carol, Julia]
Result: [Alice, Betty, Debbie, Elaine, Felicia, Carol, Georgia, Helen, Ilene, Julia]
```
---
```
Master: [snake, lizard, frog, werewolf, vulture, dog, human]
Subset: [snake, werewolf, lizard, human, dog]
Result: [snake, frog, werewolf, lizard, vulture, human, dog]
```
---
```
Master: [Pete, Rob, Jeff, Stan, Chris, Doug, Reggie, Paul, Alex]
Subset: [Jeff, Stan, Pete, Paul]
Result: [Rob, Jeff, Stan, Pete, Chris, Doug, Reggie, Paul, Alex]
```
---
```
Master: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Subset: [8, 1, 2, 12, 11, 10]
Result: [3, 4, 5, 6, 7, 8, 1, 2, 9, 12, 11, 10]
```
---
```
Master: [lol, rofl, lmao, roflmao, lqtm, smh, jk, wat]
Subset: [wat, lmao, rofl]
Result: [lol, roflmao, lqtm, smh, jk, wat, lmao, rofl]
```
## Rules
* Standard loopholes, yadda yadda, convenient I/O, blah blah.
* Even though the examples use numbers and strings, you only need to support one element type, whether that's integers, strings, or anything else with well-defined equality semantics, including heterogeneous lists if that's convenient in your language.
* You may assume both the master list and the subset list contain no duplicates
* You may assume that all items found in the subset list are found in the master list
* Either list may be empty
* You must, at minimum, support arrays up to 100 elements long.
* Reordering may be implemented in-place or through the creation of a new list/array.
Happy Golfing!
  
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 51 bytes
```
+`(\b(\w+),(\w+)\b.*¶.*\b)\3,(.*\b\2\b)
$1$4,$3
1A`
```
[Try it online!](https://tio.run/##K0otycxL/P9fO0EjJkkjplxbUwdMxiTpaR3apqcVk6QZY6yjAWLEGAE5XCqGKiY6KsZcho4J//8X5yVmp@qUpxallufnpOnkZFYlFqXoZJTmJubppOSnc0HkocJpRfnpCLVlpTklpUWpIGUQDQA "Retina 0.8.2 – Try It Online") Takes input as a comma-separated list of subwords on the first line and a comma-separated master list of words on the second line. Explanation:
```
(\b(\w+),(\w+)\b.*¶.*\b)\3,(.*\b\2\b)
```
Find two adjacent subwords where the second word precedes the first on the master list.
```
$1$4,$3
```
Move the second word to appear after the first word in the master list.
```
+`
```
Repeat until no words appear out of order.
```
1A`
```
Delete the subwords.
[Answer]
# JavaScript (ES6), ~~96 89 74~~ 71 bytes
This started as a bulky mess and was eventually shrunk to a rather concise and elegant form. I'd like to thank the *.splice()* method for its fruitful collaboration on that one. ;)
Takes input as `(master)(subset)`. Outputs by updating the master list.
```
m=>s=>s.map(p=x=>m.splice(p,0,...m.splice(i=m.indexOf(x),p>i||!(p=i))))
```
[Try it online!](https://tio.run/##hVJNb5tAEL37V2xPBmmLMG7SWhGW0jT9ujRKj4jDGhZYZz/oArHbpr/dndklGEWqaizNm5n3ZoZh9uyRdYUVbf9am5KfqvSk0m0H/0ixNmjTY7pVUddKUfCgpTGNomjyRaoioUt@/FYFx5C2W/H09Ao0IoTf6SpbEJKRbEVJQsk6pyTLSU59cBPHEH8DicsNJav1@i16MZIuN/@lUbIBN7m48HxwHQ/zZ@3YFwSUOGKCdkovWdtKvqRkuWMaHkQFs9b0iMqheEDLJW8bpvslFpiiXjqrdY37wMx73vc/EdwwaySCD3y3Ey53K5nQDn3kwBeu5SdubO3hZ2imEXwB63hfBwkp13oqPNNOPUbeeZ5OswdXQYpfzJaIKmtqtAdu@cHICvHjIPvBOmLps82gmPYdpxpzxbmeZ47KWes73jvVvdm50XjlhN97z75prOjcXszgOt7zuvb7uWODe5tryY9@hJfi59qO@Y8vDadCCZzJO7gKOAm4lRWeRoIFIea5q2QMx7PJpV@mNZWzUjHz7I9Q/ugV2k41aPbuGA5svA4EL3Q45CJfRJWxt6xogiBTlHR5SNIt@U2qQIVBF16RwujOSB5JUwcq2huhA6wQhuRPePoL "JavaScript (Node.js) – Try It Online")
### How?
We are using two nested *[.splice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)* methods on the same array to conditionally move an element from position \$i\$ to position \$p\$:
```
m.splice(p, 0, ...m.splice(i, condition))
```
If the condition is truthy (coerced to \$1\$):
* the inner *.splice()* removes and returns the element at position \$i\$ as a singleton array \$[element]\$
* thanks to the [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax), this element is expanded as a 3rd argument for the outer *.splice()*, which causes it to be inserted back at position \$p\$
If the condition is falsy (coerced to \$0\$):
* the inner *.splice()* removes nothing and returns an empty array
* as a result, the outer *.splice()* receives *undefined* as its 3rd argument and nothing is inserted either
### Commented
```
m => s =>                 // m[] = master list, s[] = subset list
  s.map(                  //
    p =                   // p = position in the master list of the last element from
                          //     the subset list (initialized to a non-numeric value)
    x =>                  // for each element x in the subset list:
    m.splice(             //   insert in the master list:
      p,                  //     at position p
      0,                  //     without removing any element
      ...m.splice(        //     remove from the master list and flatten:
        i = m.indexOf(x), //       i = position of x in the master list
        p > i             //       if p is greater than i, remove x from its current
                          //       position and insert it at position p
        || !(p = i)       //       otherwise, set p to i and don't remove/insert anything
      )                   //     end of inner splice()
    )                     //   end of outer splice()
  )                       // end of map()
```
[Answer]
## Haskell, 79 bytes
```
(m:n)#u@(s:t)|m==s=m:n#t|all(/=m)u=m:n#u|(x,_:z)<-span(/=s)n=(x++s:m:z)#u
m#_=m
```
[Try it online!](https://tio.run/##jVLbbtNAEH3vV1g2D7Y6FbbTpnVUS5QCBZ6q8lhF1SbZxCZ7MXshocq/h5l1Am1TJGRpz@zMOWfWs9swu@RCbLepHKks8e9SO3LZRta1rTGTuA0TIn1by8yHvd@ka3gYPWaXJ7ZjCis2U3W6Pj62I4npxB/J5KGWW8laFdXRTB9FUWda5aI3UZpk0X0BJQzG0f34ZaHK8wJOSxhWUAwG5xjmSBtW/0OEqoLy7CzwIdSpMn61N5wCEUtcX9Zj1nWCxxBPmMIPgykzRjsMZn66ROCCdw1TLkaHfa4XHZpdiXZKZu@5c78Qr5nRAvEDn0xaKnwUOCQKPnGkttTvhmuzCNFnbKUQvyAQ56sXmKe2e7@/qr3zjnNwEqvYkjxE@8jMDIO50QuEFTd8pcUcw59eOG@INAulxkumQru9@An5j0/P6jWHbW@5I@GdntDZ@Jyk31wQXDemtTQL7anbHV8swkhumacfuRJ8HZo/V@0MA@nflwtDOIcLwNeRQ4EvoUSjC6ByUYZEfnhUEeZn9JxASKZ3uz4SP5xEsLLB9Tvd@Yr1T4DwmSAeb38D "Haskell – Try It Online")
```
(m:n)#u@(s:t)                 -- m: head of master list
                              -- n: tail of master list
                              -- s: head of subset
                              -- t: tail of subset
                              -- u: whole subset
   |m==s                      -- if m==s
        =m:n#t                -- return 'm' and append a recursive call with 'n' and 't'
   |all(/=m)u                 -- if 'm' is not in 'u'
             =m:n#u           -- return 'm' and append a recursive call with 'n' and 'u'
   |                          -- else (note: 's' is element of 'n')
    (x,_:z)<-span(/=s)n       -- split 'n' into a list 'x' before element 's' and
                              -- a list 'z' after element 's' and
       = (x++s:m:z)#u         -- make a recursive call with
                              -- x++s:m:z as the new master list (i.e. 'm' inserted into 'n' after 's') 
                              -- and 'u'
m # _ = m                     -- if either list is emtpy, return the master list
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~73~~ 68 bytes
```
->a,b{0while b.zip(a&b).find{|m,n|m!=n&&a=a[0..a.index(m)]-[n]|a};a}
```
[Try it online!](https://tio.run/##ZY2xTsMwEIZ3nsJkiFrpatkxASIUJAQTUwWj5cEWdmopcavSiELTZw93KZmYft9/33fe9@57DPW4erTgTuJrE1vPHP@Ju4XN3ZKHmD5OQwdp6K7rlOe2tlpwbjn2/rjolmalkxns@cGexx0LWisoQBrQElMZczWVlRAS2E0B7LYCJpW6o0kAq3AsytIA07S5cLSfTRzRUogDK1EHhuo9koihLwkvSMfuwsrirxbzjWztDz4Dlr1tHcWrD4Hy/WAT5fNmHz/p8bLtm4nzTRMnY237lvKp9ceMvvknz7cn0pjxFw "Ruby – Try It Online")
### How?
* The intersection between `a` and `b` contains all elements of `b`, but in the same order as we would find them in `a`
* So, if we iterate on `b` and on the intersection in parallel, as soon as we find a difference, we can relocate a single element.
* Relocation is done by cutting `a` on the position of the element we found in `b`, then removing the element we found in the intersection, and then adding the remainder of a.
* Repeat from the beginning, until all elements of `b` are in the right order in `a`
[Answer]
# [Python 2](https://docs.python.org/2/), ~~124~~ ~~109~~ ~~106~~ ~~99~~ 96 bytes
```
def f(a,b,i=0):
 while b[i+1:]:x,y=map(a.index,b)[i:i+2];i+=1;x>y>a.insert(x,a.pop(y))
 return a
```
[Try it online!](https://tio.run/##ZZBBT4NAEIXv/RUTLkA6adjFqqVpE6MnT40eCYclLLCRLmQLFvzzuANqSTy92Xnve5NsM7Rlrfk4ZjKH3BOYojoEfrSCa6kqCWms1ixKoh6Hw1k0ntgonckeUz9WkVrzZK/WB7bvj8ORrIs0rdej2DR14w2@vwIj285oEGNjlG7tiThEjizBmFkNE3/1Z@yCgCHccYT7HQILwwd6BQg7@@TbbYIQkzPnyF/SdmXJ0CIIW1uBYPFHm7ZR28EI4VRhd3OW8Z91sOxxTrKVDoLzVqckrzLPSd9boUmfS6MuNLzUXTHlZFGoiTiJriJ9qmTv0Kl/8G/3lFxedS9afEgXwa3UlzAZTbmpC9KrNPJaVznNn11l/3MKZrNbdmehXbp261gSt745@UMm/vgN "Python 2 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 40 bytes
```
{*.permutations.first(*.grep(.any)eq$_)}
```
[Try it online!](https://tio.run/##fYvdCoIwFMfve4pzEbGJiGUakvkiEnGqmdXm5pyERM9umwXSTZyL8//6KaZ5MogeFiXshqcXKKZFZ9BcZd0G5VW3hnjBRTNFAqx7ypr5gb6GFnsoSbGnpFj6sPIh2tPt7JsmqcvTMLTV2nZJ6sMyijbOhT87Hz4r1/5h7MzaVRxPcHbuTndApTjLKclGAUes7cEJtZYGxgXjTFVYm3wiH2iAC5SgZckdzCUf9ZS6zxsjoBUV3O5gkZwObw "Perl 6 – Try It Online")
Anonymous code block that takes the input curried (like `f(subList)(masterList)`, and finds the first lexographical permutation of the indexes of the master list where the elements from the sub list are in the correct order. 
Intuitively, the first satisfying permutation will leave the correctly ordered elements in the original order, while moving the incorrectly placed ones the minimum needed distance forward in order to have them in the correct order, which places them directly after the previous element in the subset.
### Explanation:
```
{*                                     } # Anonymous code block that returns a lambda
  .permutations                          # In all permutations of the master list
               .first(                )  # Find the first permutation
                     (*.grep(.any)       # Where the order of the subset
                                  eq$_   # Is the same as the given order
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
Œ!iⱮṢƑ¥ƇḢ
```
[Try it online!](https://tio.run/##y0rNyan8///oJMXMRxvXPdy56NjEQ0uPtT/csej/4eWR//8r5eTnKOkoFeWngaic3MR8KA/CyiksyQVSxbkZQDIrG0iUJ5Yo/QeTKMqVAA "Jelly – Try It Online") or [Test suite](https://tio.run/##fZC/ToNQFMZ3ngKZb2ILtoZZJ6emToYw3JbLv164eAGJTo1LZ511aWJcjImbXW3se5QXwXO4YOxiSO75zjm/7zsJMeP8tmm@H4@i@uN9v1nvHr5edqv957rZvh7H9fKJ6PXyWduu6vu3q6ZxnCHRTaJbLtEcV3OJozn2YADDE5iObaIPLesUuwESY/t/hug2tOZopGBoWw73nbE7BzTRW8rEqnYGzTLODGLMaAofiDmVUhQgvHK@gMI4y0KaFgY6@6Fy9Rl5SheYwaM7Kj0QvhQBlIpJVgnug7wpeVFKhLx2FZYJTVVk7/5D/wYpTJn6axNWID4VM3gvmI@Gy6LFzkIZ5VDPRYlHpiwIImQntOTq2CHfRal1F88Fh5EUPhaeUNF1SvHrIoGSJyG8Mf6Kina/BsWBAyN/AA)
Inefficient, particularly with large master lists. Generates all possible permutations, filters out those where the subset is in the wrong order, and then returns the first. 
### Explanation
```
Œ!        | Generate all permutations of the master list
      ¥Ƈ  | Filter including only those where...
  iⱮ      |   the index of each sublist item in this permutation...
     Ƒ    |   is...
    Ṣ     |   in order. 
        Ḣ | Finally take the first item
```
[Answer]
# [J](http://jsoftware.com/), 49 bytes
```
[:(<@({:+i.@>:@-/)@i.~C.])^:(>/@i.~)&.>/]|.@;2<\[
```
[Try it online!](https://tio.run/##bU67DoIwFN35ihMHaaOUUl5SkTQhcXJyRVyMRFz8AI2/jqVF0IShyT3Pnnu3YG6DnYSLNTikfh5DeTzsu0qSXJGnXLVMFVJ5PlUte5espmdJCr8HdMkKv34xtRX5qeqo41wvtwdIHkAgpPB0r4sGBo5ixnmASCDJEIRhqk9urBo3mBHHoKWN46shyyDi2OTJr0jnuwb//1BEGBpEfwx7exaj0cIEKTZG1pUCgf7LbieWnbgGZGqxMR3hRhbU6T4 "J – Try It Online")
## explanation
We take the subset as the left arg and the full input as the right.
We'll work through the code with a specific example for clarity:
```
5 2 4 f 1 2 3 4 5
```
Take the boxed infixes of size two of the subset:
```
2 <\ [
```
producing:
```
┌───┬───┐
│5 2│2 4│
└───┴───┘
```
append them to the original input, and reverse the whole thing:
```
] |.@;
```
We get:
```
┌───┬───┬─────────┐
│2 4│5 2│1 2 3 4 5│
└───┴───┴─────────┘
```
Solving the problem becomes a right to left reduction on the above. We need
only find the right verb to insert `/` between the items.
Each iteration of the reduction will update the rightmost box (the full input,
which we're transforming) so it conforms to the ordering constraint represented
by the pair to its left. When the reduction is finished, the input will
respect the complete subset ordering.
If the ordering of the pair is the same as ordering in the input, the following
will evaluate to 0 and we'll do nothing:
```
^:(>/@i.~)
```
Otherwise it will evaluate to 1 and we'll apply the verb to the left of `^:`
```
   {: + i.@>:@-/)@i.~ C. ]
```
which moves the left item to the right of the right item. This movement is
simply a *cyclic permutation* of all the items between (and including) the two
elements in question.
J has primitive to apply such a cyclic permutation:
```
<cyclic permutation definition> C. ]
```
and the remainder of the verb does nothing but pick out the indexes we need to
cycle:
```
{: + i.@>:@-/)@i.~
```
which seems longer than it should be, but I wasn't able to golf that phrase
further.
Finally we rebox the result `<@` and we're done.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes
```
i@€MƤFṬœṗƲḊ;JḟF}W€ʋ@¥ṢFị
```
[Try it online!](https://tio.run/##y0rNyan8/z/T4VHTGt9jS9we7lxzdPLDndOPbXq4o8va6@GO@W614UC5U90Oh5Y@3LnI7eHu7v@Hl0f@/69UnliipKOUk5uYD6SK8tNylP4r5eTnwDgoUhBWTmFJLpAqzs0AklnZQAJkBgA "Jelly – Try It Online") or [Test suite](https://tio.run/##fVFNS8NAEL33V4SeB0xSWw1e6lf9AEH0IBJ62LbbNnWbrdvEqiCIF0GPHrwogiheevLU4k3Rg/8i/SNxZpP4cZGQvDc7781MdjpciKM49sqTs@HGx0MlGg/fr6Lx9cdzNLqYW49Gd5WTHcx9XpZfH6PxfSV6uYzfnspTncnpDRiT09vc2znmd@PYdS0wbDAKVci51VwV3JzrmCYeTuNpyQHDKhRmKDJJUXL@14DhYGgXi4kYQ62jfGpM26EaDK2yCZNcnvV6guchX2M@PkjqTCkZIGmE9T0ELnivzfwgT87sMHFlNeaFV6caCzwIjhAXmZICcYnXah4llgXzfCIVjlKP2qxwqVqarWIHH3ENgTTrocBz3S0r@GPLSqeidIC@z/bIKrxjphpImkq2EAZc8YEUTaQHoQhCRaKGTrXDLvOTLpn7l/q7UCJLTFm3TR6QfEvWaBDeJMN2oGWLbeX16c9lSE22eKulL2CThTT1vOCHSc@/trSiVn0vzYYCTEMRSjADs@CAZYJlgWWTfxYXrLdq0UvrNrPphL4fJZsEostkGiVM7AddhH63jd8OrXLA0tUS@eOgUb4A "Jelly – Try It Online")
### Explanation
A dyadic link that takes the subset as the left and master list as right arguments. The below example uses 9001, 42, 69, 1337, 420, 99, 255 as master and 69, 9001, 1337 as subset. 
```
i@€                      | Find the index of each subset item in the master list [3, 1, 4]
         Ʋ               | Previous 4 links as a monad
   MƤ                    | Find the index of the maximum for each prefix of this list [1, 1, 3]
     F                   | Flatten (because the previous result are actually each length one lists)
      Ṭ                  | Convert to a boolean list [1,0,1]
       œṗ                | Partition the [3, 1, 4] list before each 1 [[], [3, 1], [4]]
          Ḋ              | Remove the empty first list [[3, 1], [4]]
                    ¥    | Previous two links as a dyad
                  ʋ@     | Previous 4 links as a dyad with reversed arguments
            J            | Sequence along the master list [1, 2, 3, 4, 5, 6, 7]
             ḟF}         | Filter out items in the flattened [3, 1, 4] list
                W€       | Wrap each item as a list [[2], [5], [6], [7]]
           ;             | Concatenate rhis to the [[3, 1], [4]] list
                     Ṣ   | Sort (effectively by first item in each list) [[2], [3, 1], [4], [5], [6], [7]]
                      F  | Flatten
                       ị | Look up in original master list (and implicitly output)
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 118 bytes
```
a=>b=>{for(int j;b.Any();)foreach(var e in b.Intersect(a.Take(j=a.IndexOf(b.Dequeue())))){a.Remove(e);a.Insert(j,e);}}
```
[Try it online!](https://tio.run/##jVJNS8NAEL3nVyw9bWANSWrVkG6gIIJQ8APBQ@lhs04wFbeYbKtS9rfH2SSapK1oLpl5782bSWZkeSLLvLraKDmd56We5konbCZ1vlbTuw1soEaSJOOV4EnKk122LihiZBWn3kx9Ujd2EQIhn@lWFARIrkjqXSsNRQlSU@E9iBegKy4QfIKPm4ym3iW8WXPq2mcnvHt4XW@BghtbVQmFpiuGmTFV7FhbDaUuCScK3hfLndO@SJsHjISMjA1rEBxBL/wlO@AdVOyVRr6P7CnSZxEjwXh8bjPfdMVnUS/5Tf5/Z0YiTMPJZNAC0VpuZT3iu7oj9zyO9G0/FoWM9JuEw3Qo@8sHx2AEm19gaxwEJwjsQGHPEKmmJAhbtv8XD30acTTQO8bETv@c7N7tRdX7d4mdzsKC2zX/XCy1NG7cjVs@rfnugBtB0AnkMYOw4TMqXJrW4W2BLKZdLOv4scg1zHMFdMQ5HyFmqi8 "C# (Visual C# Interactive Compiler) – Try It Online")
Leveraging some classes in the `System.Collections.Generic` namespace. The master is a `List<T>` and the subset is a `Queue<T>`.
```
// a: master
// b: subset
a=>b=>{
  // continue until b is empty
  for(int j;b.Any();)
    // iterate over values that are out of order in a
    // per the head of b using loop variable e
    foreach(var e in
      // the out of order values are determined by
      // intersecting remaining values in b with
      b.Intersect(
        // values in a occurring before the current head of b
        // save the position in a to variable j and remove the head of b
        a.Take(j=a.IndexOf(b.Dequeue()))
      )
    ){
      // push back the out of order element in a
      a.Remove(e);
      a.Insert(j,e);
    }
}
```
]