// C5 example // 2004-11 using System; using C5; using SCG = System.Collections.Generic; namespace SortingPermutation { class MyTest { public static void Main(String[] args) { String[] cities = { "Tokyo", "Beijing", "Hangzhou", "Kyoto", "Beijing", "Copenhagen", "Seattle" }; IList alst = new ArrayList(); alst.AddAll(cities); foreach (int i in MySort.GetPermutation1(alst)) Console.Write("{0} ", i); Console.WriteLine(); IList llst = new LinkedList(); llst.AddAll(cities); foreach (int i in MySort.GetPermutation2(llst)) Console.Write("{0} ", i); Console.WriteLine(); Console.WriteLine("The rank of the cities:"); ArrayList res = MySort.GetPermutation1(MySort.GetPermutation2(llst)); foreach (int i in res) Console.Write("{0} ", i); Console.WriteLine(); } } class MySort { // Fast for array lists and similar, but not stable; slow for linked lists public static ArrayList GetPermutation1(IList lst) where T : IComparable { ArrayList res = new ArrayList(lst.Count); for (int i = 0; i < lst.Count; i++) res.Add(i); res.Sort(new DelegateComparer (delegate(int i, int j) { return lst[i].CompareTo(lst[j]); })); return res; } // Stable and fairly fast both for array lists and linked lists, // but does copy the collection's items. public static ArrayList GetPermutation2(IList lst) where T : IComparable { int i = 0; IList> zipList = lst.Map> (delegate(T x) { return new KeyValuePair(x, i++); }); zipList.Sort(new KeyValueComparer(lst)); ArrayList res = new ArrayList(lst.Count); foreach (KeyValuePair p in zipList) res.Add(p.Value); return res; } private class KeyValueComparer : SCG.IComparer> where T : IComparable { private readonly IList lst; public KeyValueComparer(IList lst) { this.lst = lst; } public int Compare(KeyValuePair p1, KeyValuePair p2) { return p1.Key.CompareTo(p2.Key); } } } }