6 using SCG = System.Collections.Generic;
8 namespace SortingPermutation
12 public static void Main(String[] args)
15 { "Tokyo", "Beijing", "Hangzhou", "Kyoto", "Beijing", "Copenhagen", "Seattle" };
16 IList<String> alst = new ArrayList<String>();
17 alst.AddAll<String>(cities);
18 foreach (int i in MySort.GetPermutation1(alst))
19 Console.Write("{0} ", i);
21 IList<String> llst = new LinkedList<String>();
22 llst.AddAll<String>(cities);
23 foreach (int i in MySort.GetPermutation2(llst))
24 Console.Write("{0} ", i);
26 Console.WriteLine("The rank of the cities:");
27 ArrayList<int> res = MySort.GetPermutation1(MySort.GetPermutation2(llst));
28 foreach (int i in res)
29 Console.Write("{0} ", i);
36 // Fast for array lists and similar, but not stable; slow for linked lists
38 public static ArrayList<int> GetPermutation1<T>(IList<T> lst)
39 where T : IComparable<T>
41 ArrayList<int> res = new ArrayList<int>(lst.Count);
42 for (int i = 0; i < lst.Count; i++)
44 res.Sort(new DelegateComparer<int>
45 (delegate(int i, int j) { return lst[i].CompareTo(lst[j]); }));
49 // Stable and fairly fast both for array lists and linked lists,
50 // but does copy the collection's items.
52 public static ArrayList<int> GetPermutation2<T>(IList<T> lst)
53 where T : IComparable<T>
56 IList<KeyValuePair<T, int>> zipList =
57 lst.Map<KeyValuePair<T, int>>
58 (delegate(T x) { return new KeyValuePair<T, int>(x, i++); });
59 zipList.Sort(new KeyValueComparer<T>(lst));
60 ArrayList<int> res = new ArrayList<int>(lst.Count);
61 foreach (KeyValuePair<T, int> p in zipList)
66 private class KeyValueComparer<T> : SCG.IComparer<KeyValuePair<T, int>>
67 where T : IComparable<T>
69 private readonly IList<T> lst;
70 public KeyValueComparer(IList<T> lst)
74 public int Compare(KeyValuePair<T, int> p1, KeyValuePair<T, int> p2)
76 return p1.Key.CompareTo(p2.Key);